TypeScript 7 reference · Type Operators and Keywords
TypeScript mapped types ({ [K in Keys]: … }) Operator
Create a new object type by transforming every property of another, the way Partial and Readonly are built.
TypeScript 7 Since 2.1
Syntax
{ [K in keyof T]: NewType }
Examples
type Flags<T> = { [K in keyof T]: boolean };
interface Features {
darkMode: string;
beta: number;
}
const enabled: Flags<Features> = { darkMode: true, beta: false };
console.log(enabled);
Output
{ darkMode: true, beta: false }type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] };
interface Person {
name: string;
age: number;
}
const p: Getters<Person> = { getName: () => "Ana", getAge: () => 34 };
console.log(p.getName(), p.getAge());
Output
Ana 34
Version history
| Version | Change |
|---|---|
| TypeScript 2.1 | Added |
Related
keyof· Produce a union of an object type's property names: keyof { a: 1; b: 2 } is 'a' | 'b'.Partial<Type>· Make every property of a type optional. Useful for update functions that accept only the fields that change.template literal types· Build string literal types with template syntax: `on${string}` or combinations of unions like `${Size}-${Color}`.- TypeScript keyof, typeof and Indexed Access · tutorial