TypeScript高级类型Readonly, Required,Partial, Pick, Record

以 Person 为例
interface Person {
    name: string;
    age?: number;
}
Partial

源码:

type Partial = {
    [P in keyof T]?: T[P];
};

实例:

type Person2 = Partial;
// Person2 === {name?: string; age?: number}
Required

源码:

type Required = {
    [P in keyof T]-?: T[P];
};

实例:

type Person3 = Required;
// Person3 === {name: string; age: number}
Readonly

源码:

type Readonly = {
    readonly [P in keyof T]: T[P];
};

实例:

type Person4 = Readonly;
// Person4 === {readonly name: string; readonly age?: number}
Pick

源码:

type Pick = {
    [P in K]: T[P];
};

实例:

type Person5 = Pick;
// Person5 === {name: string}
Record

源码:

type Record = {
    [P in K]: T;
};

实例:

type Person6 = Record<'name' | 'age', string>;
// Person6 === {name: string; age: string}

你可能感兴趣的:(TypeScript高级类型Readonly, Required,Partial, Pick, Record)