Mapped types allow you to create new object types by iterating over keys of an existing type using the [K in keyof T] index signature operator.
[K in keyof T]: Iterates over keys in T.readonly [K in keyof T]: Makes all properties read-only.[K in keyof T]?:: Makes all properties optional.-readonly or -?: Removes modifiers.as key remapping: [K in keyof T as NewKey] (Remaps or filters keys).interface User {
id: number;
name: string;
email: string;
}
// Custom implementation of Readonly<T> using Mapped Type
type MyReadonly<T> = {
readonly [K in keyof T]: T[K];
};
// Custom implementation of Optional<T>
type MyPartial<T> = {
[K in keyof T]?: T[K];
};
// Key Remapping using 'as' & Template Literals
type GetterMethods<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type UserGetters = GetterMethods<User>;
// Generates:
// {
// getId: () => number;
// getName: () => string;
// getEmail: () => string;
// }
const userGetters: UserGetters = {
getId: () => 101,
getName: () => "Alice",
getEmail: () => "[email protected]"
};
console.log("User Email:", userGetters.getEmail());
as never to Filter Keys: Exclude specific properties during mapping by mapping their key to never.Capitalize, Uncapitalize, Uppercase, Lowercase).Create a mapped type Nullable<T> that maps every property K of T to T[K] | null.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With