Mapped and conditional types are advanced features in TypeScript that enhance the type system's expressiveness and flexibility. They allow developers to create types that are derived from existing types, enabling more dynamic and reusable code. Understanding these concepts is crucial for building robust applications with TypeScript.
Mapped types allow you to create new types by transforming properties of an existing type. They are defined using the syntax of an object type, but with a special syntax that iterates over the keys of the original type.
type MappedType = {
[K in keyof T]: T[K];
};
In this example, K iterates over each key in the type T, and the new type will have the same properties as T.
type Person = {
name: string;
age: number;
};
type ReadonlyPerson = {
readonly [K in keyof Person]: Person[K];
};
Here, ReadonlyPerson is a mapped type that makes all properties of Person readonly. This is useful for ensuring that objects cannot be modified after their creation.
Partial, Required, and Pick.Conditional types allow you to define types based on a condition. They are expressed using the syntax T extends U ? X : Y, where T is the type being checked, U is the type to compare against, and X and Y are the resulting types based on the condition.
type IsString = T extends string ? "Yes" : "No";
In this example, IsString checks if the type T is a string. If it is, it resolves to "Yes"; otherwise, it resolves to "No".
Mapped and conditional types can be combined for even more powerful type transformations. For example, you can create a type that only includes properties of a certain type.
type Filtered = {
[K in keyof T]: T[K] extends string ? T[K] : never;
};
This Filtered type will create a new type that only includes properties of type string from the original type T.
In conclusion, mapped and conditional types are essential tools in TypeScript that enable developers to create flexible and reusable types. By understanding and applying these concepts, you can significantly improve the type safety and maintainability of your applications.