Published on

Typescript 高级类型一

Authors

常用的Partial, Readonly, Record, Pick

源码定义

/**
 * Make all properties in T optional
 */
type Partial<T> = {
    [P in keyof 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;
};

Record

以 typeof 格式快速创建一个类型,此类型包含一组指定的属性且都是必填

type SystemLocation = Record<'x' | 'y', number>;
// 等同于
type SystemLocation = {
	x: number;
	y: number;
}

具体的复杂业务场景中,一般会与接口 Pick 、Partial 等组合使用,从而过滤和重组出新的类型定义

Partial

将类型定义的所有属性都修改为可选。

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

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

Readonly

将所有属性定义为自读。

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

// 等同于
type SystemLocation = {
    readonly x: number;
    readonly y: number;
}

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

Pick

从类型的定义中选择部分类型,返回一个新的类型组合

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

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