美文网首页
TypeScript高级类型Readonly, Required

TypeScript高级类型Readonly, Required

作者: 微志异 | 来源:发表于2020-02-05 21:22 被阅读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}

相关文章

网友评论

      本文标题:TypeScript高级类型Readonly, Required

      本文链接:https://www.haomeiwen.com/subject/ztjexhtx.html