When defining interfaces in typescript (ts), you often need to repackage or repackage them. Ts has added program-type tools to make it easier for developers to do this in version 2.1.
Note: These program types are restricted to type declarations only.
Take a look at their source definitions:
/** * Make all properties in T optional */
type Partial<T> = {
[P inkeyof T]? : T[P]; };/** * Make all properties in T readonly */
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
/** * From T, pick a set of properties whose keys are in the union K */
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
/** * Construct a type with a set of properties K of type T */
type Record<K extends keyof any, T> = {
[P in K]: T;
};
Copy the code
These application types were released back in 2016 and are already used by many frameworks or plug-ins. So to explain in turn:
Record
Quickly creates a type in Typeof format that contains a specified set of properties and is mandatory.
type Coord = Record<'x' | 'y'.number>;
/ / is equivalent to
type Coord = {
x: number;
y: number;
}
Copy the code
In complex service scenarios, interfaces such as Pick and Partial are used together to filter and reorganize new type definitions.
Partial
Make all attributes of the type definition optional.
type Coord = Partial<Record<'x' | 'y'.number> >;/ / is equivalent to
typeCoord = { x? :number; y? :number;
}
Copy the code
Readonly
It makes sense both literally and by definition: make all attributes self-readable.
type Coord = Readonly<Record<'x' | 'y'.number> >;/ / is equivalent to
type Coord = {
readonly x: number;
readonly x: number;
}
// If you make a change, you will get an error:
const c: Coord = { x: 1, y: 1 };
c.x = 2; // Error: Cannot assign to 'x' because it is a read-only property.
Copy the code
Pick
Returns a new type definition by selecting the specified set of properties from the properties of the type definition.
type Coord = Record<'x' | 'y'.number>;
type CoordX = Pick<Coord, 'x'>;
/ / used to
type CoordX = {
x: number;
}
Copy the code
There are many other advanced types that have been added to the official preset: all TypeScript advanced types.