...

/

Mapped Types

Mapped Types

Learn about TypeScript's generic syntax, the keyof keyword, and predefined mapped types (Partial, Required, Readonly, Pick, and Record) for creating new types based on existing ones.

Introduction to mapped types

We can use a type alias to define a special named type. Type aliases, however, can become even more powerful when combined with generic syntax, allowing us to create types based on other types.

Add in the keyof keyword, and we can create new types based on the properties of another type.

This is best illustrated with an example as follows:

interface IAbRequired {
a: number;
b: string;
}
// Create a variable ab that conforms to the IAbRequired interface
let ab: IAbRequired = {
a: 1,
b: "test",
};
// Define a generic type WeakInterface that makes all properties of a given type optional
type WeakInterface<T> = {
[K in keyof T]?: T[K];
};
// Create a variable allOptional of type WeakInterface<IAbRequired> and initialize it as an empty object
let allOptional: WeakInterface<IAbRequired> = {};
Using the keyof operator to create a new type
  • We define an interface named IAbRequired on lines 1–4 that has two properties named a of type number and b of type string.

  • We then create an instance of an object named ab on lines 7–10, which is of type IAbRequired, and as such, must define both an a and b property since both properties are required.

  • We then create a type alias name WeakInterface from lines 13–15, which uses generic syntax to allow it to be used with any type named T. This type alias also specifies a second type, K, that uses the keyof keyword on the type T. The effect of the keyof keyword is that the WeakInterface type will contain a property for each property that the type T defines.

Note: Take a closer look at the definition of the properties on line 14, that is [K in ...