Skip to Content
Learning TypeScript 2.x - Second Edition
book

Learning TypeScript 2.x - Second Edition

by Remo H. Jansen
April 2018
Beginner content levelBeginner
536 pages
13h 21m
English
Packt Publishing
Content preview from Learning TypeScript 2.x - Second Edition

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering TypeScript - Fourth Edition

Mastering TypeScript - Fourth Edition

Nathan Rozentals
Learning TypeScript

Learning TypeScript

Josh Goldberg
TypeScript for Beginners

TypeScript for Beginners

Bharath Thippireddy

Publisher Resources

ISBN: 9781788391474Supplemental Content