将 Typescript 接口中的所有属性设为可选

编程入门 行业动态 更新时间:2024-10-26 04:29:30
本文介绍了将 Typescript 接口中的所有属性设为可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的应用程序中有一个接口:

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 接口中的所有属性设为可选

本文发布于:2023-06-12 05:15:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/651998.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:设为   可选   属性   接口   Typescript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!