Mapped Types in TypeScript
Mapped Types in TypeScript
Section titled “Mapped Types in TypeScript”What are Mapped Types?
Section titled “What are Mapped Types?”Mapped types create new types by iterating over the keys of an existing type and transforming each property. Think of them as Array.map() but for types.
Basic Mapped Type
Section titled “Basic Mapped Type”// Make all properties readonlytype Readonly<T> = { readonly [K in keyof T]: T[K];};
// Make all properties optionaltype Optional<T> = { [K in keyof T]?: T[K];};
// Make all properties nullabletype Nullable<T> = { [K in keyof T]: T[K] | null;};Built-in Mapped Types
Section titled “Built-in Mapped Types”interface User { name: string; age: number; email: string;}
// All readonlytype ReadonlyUser = Readonly<User>;// { readonly name: string; readonly age: number; readonly email: string }
// All partialtype PartialUser = Partial<User>;// { name?: string; age?: number; email?: string }Transforming Property Types
Section titled “Transforming Property Types”// Convert all properties to stringstype ToString<T> = { [K in keyof T]: string;};
// Make all properties return Promisestype Promisify<T> = { [K in keyof T]: Promise<T[K]>;};
// Deep readonlytype DeepReadonly<T> = { readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];};Key Remapping via as
Section titled “Key Remapping via as”// Add prefix to all keystype AddPrefix<T, P extends string> = { [K in keyof T as `${P}${Capitalize<string & K>}`]: T[K];};
type User = { name: string; age: number };type PrefixedUser = AddPrefix<User, "user">;// { userName: string; userAge: number }Filtering Keys
Section titled “Filtering Keys”// Only string valuestype StringKeys<T> = { [K in keyof T as T[K] extends string ? K : never]: T[K];};
// Remove functionstype OnlyData<T> = { [K in keyof T as T[K] extends Function ? never : K]: T[K]>;};Real Project Example
Section titled “Real Project Example”// Form validation statesinterface FormFields { username: string; password: string; email: string;}
// Transform form fields into validation statetype FormValidation<T> = { [K in keyof T]: { value: T[K]; error: string | null; touched: boolean; dirty: boolean; };};
type SignupFormState = FormValidation<FormFields>;Interview Questions
Section titled “Interview Questions”Easy: What is a mapped type?
Medium: How does keyof work in mapped types?
Hard: How would you create a DeepReadonly mapped type?