Typescript mapped types
Created By: chatGPT
In TypeScript, mapped types allow you to create new types by transforming properties of an existing type. This is particularly useful for modifying properties or creating variations of types without changing the original type structure.
// Basic mapped type example
interface Person {
name: string;
age: number;
}
type ReadonlyPerson = {
readonly [K in keyof Person]: Person[K];
};
In this example, the
ReadonlyPerson
type makes all properties of the Person
type readonly. We use keyof
to iterate over the keys of the Person
interface.// Using mapped types with optional properties
type OptionalPerson = {
[K in keyof Person]?: Person[K];
};
Using the mapped type, we can create an
OptionalPerson
type where all properties of Person
are now optional. This is done by appending a question mark to the property definition.// Conditional mapped types
type PersonType = 'adult' | 'child';
type PersonRole = {
[K in PersonType]: K extends 'adult' ? 'Responsible' : 'Dependent';
};
Here we define a
PersonRole
type that dynamically assigns a value based on whether the type is 'adult' or 'child'. The mapped type employs a conditional type to set different values depending on the key.// Example of using mapped types with interfaces
interface Permissions {
read: boolean;
write: boolean;
}
type AdminPermissions = {
[K in keyof Permissions]-?: true;
};
In
AdminPermissions
, we're using the minus operator (-?
) to remove optional modifiers, ensuring all properties are required and set to true
.// Creating a mapped type for transforming types
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
Lastly, with the
Nullable
mapped type, we can transform any given type to allow null values for each of its properties. This is achieved by using a union type with null
.// Example usage
interface User {
id: number;
name: string;
}
type UserNullable = Nullable<User>;