Composing Types

Build bigger types out of smaller ones rather than repeating yourself.

& intersects: type Timestamped = { created: string } and then Book & Timestamped.

extends does the same for interfaces.

The point is the same as normalization in the SQL course: describe each fact once, so correcting it corrects everything.

Try it

Add a field to Entity and watch both Book and Author require it. That is the refactoring payoff, in miniature.

loading editor…

checking…

Author is missing created, and the compiler says so. One change to Entity now propagates to both.

◈ Graded Types

Define a type called Book with a required title (string), a required year (number), an optional subtitle (string), and a readonly id (string). Then define a type called Shelf with a name (string) and a books property that is an array of Book. Finally create a Shelf called shelf containing exactly one book titled Kindred from 1979 with id "b1", named "Fiction". Everything must type-check in strict mode.

Checked against the compiler, not against how you wrote it. 3 visible and 3 hidden checks.

loading editor…
real tsc, strict mode

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back