April 2018
Beginner
536 pages
13h 21m
English
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 ...