[英]Typescript mapped types
建议在显式部分类型上使用映射类型,请参阅https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types
即代替
interface PersonPartial {
name?: string;
age?: number;
}
我们会用
interface Person {
name: string;
age: number;
}
type Partial<T> = {
[P in keyof T]?: T[P];
}
type PersonPartial = Partial<Person>;
是否可以映射到另一个方向,例如
type NotPartial<T> = {
[P in keyof T]!: T[P];
}
type Person = NotPartial<PersonPartial>;
因为我有一个创建部分接口的生成,这会由于鸭子输入而破坏我的类型检查。
您可以使用-?
删除?
从同态映射类型(但继续阅读) :
interface Person {
name?: string;
age?: number;
}
type Mandatory<T> = {
[P in keyof T]-?: T[P];
}
type PersonMandatory = Mandatory<Person>;
但是,您不必这样做,因为 TypeScript 已经有了它: Required<T>
。 Required<T>
...
...条
?
来自T
所有属性的修饰符,因此需要所有属性。
所以:
interface Person {
name?: string;
age?: number;
}
type RequiredPerson = Required<Person>;
如果您查看https://www.typescriptlang.org/docs/handbook/utility-types.html,您会看到 Typescript 提供了很多实用程序类型。 所以请注意该实用程序尚未存在。 您会发现“ Required
最适合您的场景。
如果你想了解更多,我在这里写了一篇关于映射类型的文章
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.