TypeScript高级类型Readonly, Required

2020-02-05  本文已影响0人  微志异
以 Person 为例
interface Person {
    name: string;
    age?: number;
}
Partial

源码:

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

实例:

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

源码:

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

实例:

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

源码:

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

实例:

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

源码:

type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
};

实例:

type Person5 = Pick<Person, 'name'>;
// Person5 === {name: string}
Record

源码:

type Record<K extends keyof any, T> = {
    [P in K]: T;
};

实例:

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

猜你喜欢

热点阅读