# Typescript 中的 Partial, Readonly, Record, Pick

34,179

``````/**
* Make all properties in T optional
*/
type Partial<T> = {
[P in keyof T]?: T[P];
};

/**
* Make all properties in T readonly
*/
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;
};
``````

### Record

``````type Coord = Record<'x' | 'y', number>;

// 等同于
type Coord = {
x: number;
y: number;
}
``````

### Partial

``````type Coord = Partial<Record<'x' | 'y', number>>;

// 等同于
type Coord = {
x?: number;
y?: number;
}
``````

``````type Coord = Readonly<Record<'x' | 'y', number>>;

// 等同于
type Coord = {
}

// 如果进行了修改，则会报错：
const c: Coord = { x: 1, y: 1 };
c.x = 2; // Error: Cannot assign to 'x' because it is a read-only property.
``````

### Pick

``````type Coord = Record<'x' | 'y', number>;
type CoordX = Pick<Coord, 'x'>;

// 等用于
type CoordX = {
x: number;
}
``````