将 Typescript 接口中的所有属性设为可选 [英] Make all properties within a Typescript interface optional
问题描述
我的应用程序中有一个接口:
I have an interface in my application:
interface Asset {
id: string;
internal_id: string;
usage: number;
}
这是帖子界面的一部分:
that is part of a post interface:
interface Post {
asset: Asset;
}
我还有一个用于后期草稿的界面,其中资产对象可能只是部分构建
I also have an interface that is for a post draft, where the asset object might only be partially constructed
interface PostDraft {
asset: Asset;
}
我想允许 PostDraft
对象拥有部分资产对象,同时仍然检查那里的属性的类型(所以我不想只是用 any
).
I want to allow a PostDraft
object to have a partial asset object while still checking types on the properties that are there (so I don't want to just swap it out with any
).
我基本上想要一种能够生成以下内容的方法:
I basically want a way to be able to generate the following:
interface AssetDraft {
id?: string;
internal_id?: string;
usage?: number;
}
无需完全重新定义Asset
接口.有没有办法做到这一点?如果没有,在这种情况下安排我的类型的明智方法是什么?
without entirely re-defining the Asset
interface. Is there a way to do this? If not, what would the smart way to arrange my types in this situation be?
推荐答案
这在 TypeScript 中是不可能的 <2.1 无需创建具有可选属性的附加接口;但是,这可以通过在 TypeScript 2.1+ 中使用映射类型来实现.
This isn't possible in TypeScript < 2.1 without creating an additional interface with optional properties; however, this is possible by using mapped types in TypeScript 2.1+.
为此,请使用 TypeScript 默认提供的 Partial
类型.
To do this, use the Partial<T>
type which TypeScript provides by default.
interface PostDraft {
asset: Partial<Asset>;
}
现在 asset
上的所有属性都是可选的,这将允许您执行以下操作:
Now all the properties on asset
are optional, which will allow you to do the following:
const postDraft: PostDraft = {
asset: {
id: "some-id"
}
};
关于部分
部分
是定义 为映射类型,使所提供类型中的每个属性都可选(使用 ?
标记).
Partial<T>
is defined as a mapped type that makes every property in the provided type optional (using the ?
token).
type Partial<T> = {
[P in keyof T]?: T[P];
};
Read more about mapped types here and in the handbook.
深度局部
如果您想要在对象上递归工作的部分实现,那么您可以在 TS 4.1+ 中使用以下类型:
If you want a partial implementation that works recursively on objects then you can use the following type in TS 4.1+:
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};
这篇关于将 Typescript 接口中的所有属性设为可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!