typeof and Mapped type in Typescript

I was reading an article introducing the usage of the typeof and Mapped type which was introduced back in TS 2.1. It is quite interesting that typescript can actually make generic of generic and infer the types of properties and then use them for border extensions.

For typeof it basically yields the type of permitted property names. A keyof T type is considered a subtype of string. The interesting part is you can use this pattern with other parts of the type system to get type-safe lookups.

function getProperty<T, K extends keyof T>(obj: T, key: K) {
    return obj[key];  // Inferred type is T[K]
}

function setProperty<T, K extends keyof T>(obj: T, key: K, value: T[K]) {
    obj[key] = value;
}

This gives a lot of possibilities when used with mapped type, which is produced by taking a union of literal types, and computing a set of properties for a new object type. For example the below code produces a Person type with all its property optional:

type Partial = {
    [P in keyof T]?: T[P];
};

type PartialPerson = Partial;

A use case in my recent project is to not only make a type partial in one level but make it recursive:


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

This blog explained the typeof pretty well.

And this one is a good description of mapped type.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s