keyof, typeof, mapped and conditional types
In the previous lesson you used utility types. Today we open the hood and see how they are built, because with the same tools you can create your own. There are four pieces: keyof, which gets the keys of a type; typeof, which gets the type of a value; mapped types, which loop over keys and generate a new type; and conditional types, which choose a type depending on a condition. It is the most advanced material of the course, so go slowly and try each example in the editor by hovering over the types.
keyof and typeof
Careful: typeof in type position is not the JavaScript typeof that returns a text. Written inside a type, typeof value gives the static type of that value. Combined with keyof and with as const, it lets you derive a union of keys or values from a real object, so you define the data once and the type stays in sync automatically. It is the pattern you saw with the enums of week 4.
const config = {
host: 'localhost',
port: 3000,
debug: true,
};
type Config = typeof config; // { host: string; port: number; debug: boolean }
type ConfigKey = keyof Config; // 'host' | 'port' | 'debug'
const colors = { red: '#f00', green: '#0f0', blue: '#00f' } as const;
type ColorName = keyof typeof colors; // 'red' | 'green' | 'blue'
type ColorValue = (typeof colors)[ColorName]; // '#f00' | '#0f0' | '#00f'
function hex(name: ColorName): ColorValue {
return colors[name];
}
console.log(hex('green'));Mapped types
A mapped type has the form { [K in keyof T]: something }. It reads like this: for each key K of T, create a property with that name and the value the right-hand side indicates. You can add or remove modifiers with + and -: -readonly removes read-only, and -? removes optionality. That is how Partial, Required and Readonly are implemented. With the as clause you can even rename the keys along the way, for example to generate method names like getName from name.
type MyPartial<T> = { [K in keyof T]?: T[K] };
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type Nullable<T> = { [K in keyof T]: T[K] | null };
type Getters<T> = {
[K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};
interface Person {
name: string;
age: number;
}
const draft: MyPartial<Person> = { name: 'Ana' };
const maybe: Nullable<Person> = { name: null, age: 30 };
const getters: Getters<Person> = {
getName: () => 'Ana',
getAge: () => 31,
};
console.log(draft, maybe, getters.getName());Conditional types and infer
A conditional type uses ternary syntax: T extends U ? X : Y. If T fits in U, the result is X; otherwise it is Y. With the infer keyword you can capture a part of the type to reuse it: that is how ReturnType works, extracting the type returned by a function. When a conditional type receives a union, it distributes over each member separately, which lets you filter unions, as Exclude does. They are powerful tools, but use them sparingly: an overly clever type is hard to debug for whoever arrives later.
type IsString<T> = T extends string ? 'yes' : 'no';
type A = IsString<string>; // 'yes'
type B = IsString<42>; // 'no'
type ElementOf<T> = T extends (infer E)[] ? E : never;
type Item = ElementOf<string[]>; // string
type MyReturnType<F> = F extends (...args: never[]) => infer R ? R : never;
type R = MyReturnType<() => number>; // number
type OnlyStrings<T> = T extends string ? T : never;
type S = OnlyStrings<'a' | 1 | 'b' | true>; // 'a' | 'b'
const x: S = 'a';
const y: Item = 'text';
const z: R = 7;
console.log(x, y, z);✎ 我的笔记
仅保存在此浏览器中。登录后可保存到账号。0/5000 字符