Mapped types in TypeScript
Building a new type by walking another's keys.
interface Settings {
theme: string;
volume: number;
}
type Nullable<T> = { [K in keyof T]: T[K] | null };
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type MaybeSettings = Nullable<Settings>;
type SettingGetters = Getters<Settings>;
const blank: MaybeSettings = { theme: null, volume: null };
How it works
[K in keyof T]iterates every property.- The value type can be transformed as it maps.
aswith a template literal renames the keys.
Keywords and builtins used here
MaybeSettingsasconstinterfacenullnumberstringtype
The run, in numbers
- Lines
- 14
- Characters to type
- 335
- Tokens
- 101
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 55 seconds.
Step 1 of 3 in Mapped types, step 4 of 12 in Type-level programming.