capypad
0 day streak
typescript / intermediate
Snippet

Mapped Types

Mapped types allow you to create new types based on the properties of an existing type. They are essential for transforming object structures dynamically.

snippet.ts
typescript
1
2
3
type Optional<T> = {
[P in keyof T]?: T[P];
};
Breakdown
1
type Optional<T>
Defines a generic type named Optional that takes a type parameter T.
2
[P in keyof T]
Iterates over each property P found in the keys of type T.
3
?: T[P]
Makes each property optional and keeps the original property type T[P].