TypeScript Advanced: The Type System
keyof, typeof and Template Literal Types
In this lesson you will
- Derive types with keyof, typeof and indexed access
- Write a safe property getter using keyof and generics
- Build string types with template literal types
Introduction
Duplication is the enemy of maintainable types. If you have a configuration object, you do not want to write out its shape twice. This lesson shows operators that derive types from things you already have, so there is one source of truth.
keyof: the keys of a type
keyof T gives a union of the property names of T, as literal types.
typeof: the type of a value
In a type position, typeof value gives the type of an existing value. This avoids writing a type by hand for something you already built.
Indexed access types
T[K] is the type of property K in T, like indexing an object but in the type world.
[number] on an array type means "the type of any element".
Quick quiz
What is keyof User when User has the properties id, name and email?
A safe property getter
Combine keyof with generics to write a function where the key must exist, and the return type follows from the key.
K extends keyof T limits the key to real property names, and T[K] makes the result as precise as it can be: asking for "age" returns a number, not a vague union.
Template literal types
A template literal type builds string types using the same backtick syntax as template strings, but at the type level.
When combined with unions, it produces every combination:
Built-in helpers Uppercase, Lowercase, Capitalize and Uncapitalize change the case of string types.
Putting it together: typed event names
Here a list of fields becomes a set of precisely typed event handler names. One change to the fields updates everything else.
TypeScript derived onNameChange and onAgeChange from name and age, and even worked out that v is a string in one and a number in the other.
Quick quiz
What is the type `${'a' | 'b'}-${'x' | 'y'}`?
Try it yourself
Create a type CssSize that accepts strings made of a number followed by px or rem, such as "16px" or "1.5rem". Use a template literal with ${number}. The stub accepts everything, so the last line does not fail yet. Fix it.
Summary
keyof Tis the union of T's property names,typeof valueis the type of a value, andT[K]is a property's type.K extends keyof TwithT[K]makes safe, precisely typed property access.- Template literal types build string types, and combine unions into every combination.
- Mapped types with
asand template literals can generate whole APIs from one list of fields.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.