Lesson 5 of 10
Type aliases
- 12 min
- 6 checks
- 3 hints
- Go to task
Goal
Naming and combining types
Explanation
With type you can give a name to any type, whether it's an object, a union or a primitive, so you can write type ID = string | number. An interface, on the other hand, only describes object shapes.
The & operator creates an intersection: the type A & B describes a value that has the fields of A and the fields of B together. It lets you build a large type out of small ones you defined once, instead of copying fields around until the copies drift apart.
The practical rule is to use interface for object shapes, and type for everything else and for combining types. Note that intersecting two conflicting fields, like { id: string } & { id: number }, isn't rejected when you define it. Instead, the type of id becomes never, so you can't create a value of that type at all.
Your task
Define type ID that accepts a string or a number, and use it as the type of id in Article. Then define StoredArticle as the intersection of Article and Timestamps, use it as the type of the first parameter of touch and of its return value, and give the second parameter the type number.
Checks
6 checks- No type errors
- ID accepts a string and a number
- ID accepts nothing else
- StoredArticle has all four fields and accepts a numeric ID
- touch rejects an article without createdAt and updatedAt
- touch changes only updatedAt