benjaminvr

Untitled

Jun 27th, 2022
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. /*
  2.  
  3. Intro:
  4.  
  5. Project grew and we ended up in a situation with
  6. some users starting to have more influence.
  7. Therefore, we decided to create a new person type
  8. called PowerUser which is supposed to combine
  9. everything User and Admin have.
  10.  
  11. Exercise:
  12.  
  13. Define type PowerUser which should have all fields
  14. from both User and Admin (except for type),
  15. and also have type 'powerUser' without duplicating
  16. all the fields in the code.
  17.  
  18. */
  19.  
  20. interface User {
  21. name: string;
  22. age: number;
  23. occupation: string;
  24. }
  25.  
  26. interface Admin {
  27. name: string;
  28. age: number;
  29. role: string;
  30. }
  31.  
  32. type PowerUser = User & Admin;
  33.  
  34. export type Person = User | Admin | PowerUser;
  35.  
  36. export const persons: Person[] = [
  37. { name: 'Max Mustermann', age: 25, occupation: 'Chimney sweep' },
  38. { name: 'Jane Doe', age: 32, role: 'Administrator' },
  39. { name: 'Kate MΓΌller', age: 23, occupation: 'Astronaut' },
  40. { name: 'Bruce Willis', age: 64, role: 'World saver' },
  41. {
  42. name: 'Nikki Stone',
  43. age: 45,
  44. role: 'Moderator',
  45. occupation: 'Cat groomer'
  46. }
  47. ];
  48.  
  49. function isAdmin(person: Person): person is Admin {
  50. return !!Object.keys(person).find(x => x === "role")
  51. }
  52.  
  53. function isUser(person: Person): person is User {
  54. return !!Object.keys(person).find(x => x === "occupation")
  55. }
  56.  
  57. function isPowerUser(person: Person): person is PowerUser {
  58. return isAdmin(person) && isUser(person)
  59. }
  60.  
  61. export function logPerson(person: Person) {
  62. let additionalInformation: string = '';
  63. if (isAdmin(person)) {
  64. additionalInformation = person.role;
  65. }
  66. if (isUser(person)) {
  67. additionalInformation = person.occupation;
  68. }
  69. if (isPowerUser(person)) {
  70. additionalInformation = `${person.role}, ${person.occupation}`;
  71. }
  72. console.log(`${person.name}, ${person.age}, ${additionalInformation}`);
  73. }
  74.  
  75. console.log('Admins:');
  76. persons.filter(isAdmin).forEach(logPerson);
  77.  
  78. console.log();
  79.  
  80. console.log('Users:');
  81. persons.filter(isUser).forEach(logPerson);
  82.  
  83. console.log();
  84.  
  85. console.log('Power users:');
  86. persons.filter(isPowerUser).forEach(logPerson);
  87.  
  88. // In case if you are stuck:
  89. // https://www.typescriptlang.org/docs/handbook/utility-types.html
  90.  
Advertisement
Add Comment
Please, Sign In to add comment