You've written this before:
interface User {
id: number;
name: string;
email: string;
role: 'admin' | 'user';
}
interface UserFormState {
id: boolean;
name: boolean;
email: boolean;
role: boolean;
}
A UserFormState where every field is a boolean — did it change? Was it touched? You maintain two types that mirror each other. Add a field to User, forget to update UserFormState, and your types lie to you.
Mapped types solve this. They let you derive one type from another automatically. When User changes, UserFormState updates itself.
Let's start with the basics and work up to the patterns that will change how you architect TypeScript code.
The Syntax: What a Mapped Type Actually Is
A mapped type iterates over the keys of another type and transforms each property. Here's the simplest form:
type Mapped<T> = {
[K in keyof T]: T[K];
};
This reads: "for each key K in the set of keys of T, create a property with that key, and give it
Discussion
Jump in and comment!
Get the ball rolling with your comment!