Typescript 中的 Partial, Readonly, Record, Pick

源码定义

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

/**
 * Make all properties in T readonly
 */
type Readonly = {
    readonly [P in keyof T]: T[P];
};

/**
 * From T, pick a set of properties whose keys are in the union K
 */
type Pick = {
    [P in K]: T[P];
};

/**
 * Construct a type with a set of properties K of type T
 */
type Record = {
    [P in K]: T;
};

Record

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

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

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

Partial

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

type Coord = Partial>;

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

Readonly

不管是从字面意思,还是定义上都很好理解:将所有属性定义为自读。

type Coord = Readonly>;

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

从类型定义的属性中,选取指定一组属性,返回一个新的类型定义。

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

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

你可能感兴趣的:(Typescript 中的 Partial, Readonly, Record, Pick)