Introduction
The utility types of the last lesson are not magic: Partial, Pick and ReturnType are written in TypeScript itself, with three tools this lesson introduces. Mapped types go over the keys of a type, conditional types choose a type by a test, and template literal types build string types from parts. With them you can write your own utilities, and read the type errors that libraries built with them produce.
How it works
Start with keyof T, the union of T's keys, and T[K], the type of property K. A mapped type goes over a union of keys and builds a property for each:
type Flags<T> = { [K in keyof T]: boolean };
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };
The ? and readonly modifiers can be added, and removed with -? and -readonly, which is how Required works. An as clause remaps keys, often with a template literal type: `get${Capitalize<string & K>}` turns volume into getVolume. The string & K keeps only string keys, since keys can also be numbers or symbols. A key remapped to never is dropped, which is how a type can filter properties.
A conditional type chooses between two types: T extends string ? "yes" : "no". Applied to a union, it is applied to each member separately and the results are joined; that is how Exclude<U, X> is written: U extends X ? never : U. Inside the test, infer names a part of the type to extract:
type ElementOf<T> = T extends (infer U)[] ? U : never; // ElementOf<string[]> is string
type MyReturnType<F> = F extends (...args: never[]) => infer R ? R : never;
Template literal types describe strings: type CssSize = `${number}px` accepts "12px" and rejects "12". Combined with unions they multiply out: `on${"Click" | "Key"}` is "onClick" | "onKey".
These tools are powerful, and easy to overuse. Most application code needs only a few small helper types; the heavy machinery belongs in libraries, where it makes the library's users' code simpler.
Example
// Mapped types, key remapping with template literal types, and conditional types.
interface Settings {
volume: number;
muted: boolean;
theme: string;
}
type Flags<T> = { [K in keyof T]: boolean }; // the same keys, every value a boolean
type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] };
type ElementOf<T> = T extends (infer U)[] ? U : never;
type IsText<T> = T extends string ? "yes" : "no";
function makeGetters(s: Settings): Getters<Settings> {
return {
getVolume: () => s.volume,
getMuted: () => s.muted,
getTheme: () => s.theme,
};
}
const changed: Flags<Settings> = { volume: true, muted: false, theme: true };
const getters = makeGetters({ volume: 7, muted: false, theme: "dark" });
const n: ElementOf<number[]> = 42;
const a: IsText<"hi"> = "yes";
const b: IsText<42> = "no";
const keys = (Object.keys(changed) as (keyof Settings)[]).filter((k) => changed[k]);
console.log(keys, getters.getTheme(), getters.getVolume());
console.log(n, a, b);Line by line
Flags<Settings>has the keys ofSettings, each with a boolean value.Getters<Settings>renames each key togetVolume,getMutedandgetTheme, with functions returning the original types.ElementOf<number[]>usesinferto extractnumber.IsText<"hi">is"yes"andIsText<42>is"no".- The run-time code only uses the values; all of these types are erased.
Expected result
[ 'volume', 'theme' ] dark 7
42 yes no
In the real world
Libraries rely on these types. ORMs map a table's column definitions to the type of a row; routers turn a path such as "/users/:id" into a params type with an id property using template literal types; form libraries map a form's fields to a type of error messages; and event emitters type each event's payload with mapped types over an events interface. Knowing how they work makes their error messages readable.
Common mistakes
- Writing a clever type nobody can read, when a plain interface would do.
- Forgetting string & K in template literal types, which fails because keys may be numbers or symbols.
- Expecting a conditional type to look at run-time values: it works on types only.
- Being surprised by distribution over unions, which wrapping both sides in square brackets,
[T] extends [U], turns off.
Best practices
- Reach for the built-in utility types first; write your own only when they do not fit.
- Name intermediate types so that each step can be hovered and checked in an editor.
- Test a complex type with a few assignments that must work and a few that must fail.
Summary
keyof and T[K] read a type's keys and properties. Mapped types build new object types over keys, with modifiers and key remapping through as. Conditional types choose a type by a test, distribute over unions and extract parts with infer, and template literal types describe string patterns. Together they are how utility types and typed libraries are written.
Quick check
Key takeaways
- Mapped types turn every property of a type into something else, keeping the keys in step.
- Conditional types choose a type by a test, and infer pulls out the part you need.
- Template literal types describe string patterns, such as event handler names.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.