Learning TypeScript 2.x
上QQ阅读APP看书,第一时间看更新

Mapped types

Mapped types are an advanced type feature that allows us to map the value of each of the properties of a type to a different type. For example, the following mapped type transforms the value of the properties of a given type to a string literal that matches the property name:

type Keyify<T> = {
[P in keyof T]: P;
};

The following function takes an object and returns a new object in which all the properties have the same names, but their values are the names of the properties:

function getKeys<T>(obj: T): Keyify<T> {
const keysArr = Object.keys(obj);
const stringifyObj = keysArr.reduce((p, c, i, a) => {
return {
...p,
[c]: c
};
}, {});
return stringifyObj as Keyify<T>;
}

interface User {
name: string;
age: number;
}

let user: User = { name: "Remo", age: 28 };
let keys = getKeys<User>(user);

keys.name; // "name"
keys.age; // "age"

TypeScript declares some commonly used mapped types for us:
// Make all properties in T optional
type Partial<T> = {
[P in keyof T]?: T[P];
};


// Make all properties in T readonly
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};


// From T pick a set of properties K
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
}

// Construct a type with a set of properties K of type T
type Record<K extends string, T> = {
[P in K]: T;
}