Lesson 5 of 10

Type aliases

Goal

Naming and combining types

01

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.

02

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
  1. No type errors
  2. ID accepts a string and a number
  3. ID accepts nothing else
  4. StoredArticle has all four fields and accepts a numeric ID
  5. touch rejects an article without createdAt and updatedAt
  6. touch changes only updatedAt
main.ts
OutputTypeScript 5.9

Loading the TypeScript compiler. This only happens once. Your browser keeps it after that.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.