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 interfacelet ab: IAbRequired = {a: 1,b: "test",};// Define a generic type WeakInterface that makes all properties of a given type optionaltype WeakInterface<T> = {[K in keyof T]?: T[K];};// Create a variable allOptional of type WeakInterface<IAbRequired> and initialize it as an empty objectlet allOptional: WeakInterface<IAbRequired> = {};
-
We define an interface named
IAbRequired
on lines 1–4 that has two properties nameda
of typenumber
andb
of typestring
. -
We then create an instance of an object named
ab
on lines 7–10, which is of typeIAbRequired
, and as such, must define both ana
andb
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 namedT
. This type alias also specifies a second type,K
, that uses thekeyof
keyword on the typeT
. The effect of thekeyof
keyword is that theWeakInterface
type will contain a property for each property that the typeT
defines.
Note: Take a closer look at the definition of the properties on line 14, that is
[K in
...