Typescript 接口可选属性取决于其他属性

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

假设我们有以下 Typescript interface:

Let's say we have the following Typescript interface:

interface Sample { key1: boolean; key2?: string; key3?: number; };

在这种情况下,key1 总是必需的,key2 总是可选的,而 key3 应该存在如果 key1 是 true 并且如果 key1 是 false 则不应该存在.换句话说,一个键的出现取决于另一个键的值.我们如何在 Typescript 中实现这一点?

In this case, key1 is always required, key2 is always optional, while key3 should exist if key1 is true and should not exist if key1 is false. In another word, a key's occurrence depends on another key's value. How can we achieve this in Typescript?

推荐答案

最直接的表达方式是使用 类型别名 而不是接口:

The most straightforward way to represent this is with a type alias instead of an interface:

type Sample = { key1: true, key2?: string, key3: number } | { key1: false, key2?: string, key3?: never }

在这种情况下,类型别名是 union 您描述的两种类型.因此,Sample 应该是第一个成分(其中 key1 为真,key3 是必需的)或第二个成分(其中 key1 为假且 key3 不存在).

In this case the type alias is the union of two types you're describing. So a Sample should be either the first constituent (where key1 is true and key3 is required) or the second constituent (where key1 is false and key3 is absent).

类型别名类似于接口,但它们不能完全互换.如果使用类型别名会导致某种错误,请在问题中添加有关您的用例的更多详细信息.

Type aliases are similar to interfaces but they are not completely interchangeable. If using a type alias leads to some kind of error, please add more detail about your use case in the question.

希望有所帮助.祝你好运!

Hope that helps. Good luck!

更多推荐

Typescript 接口可选属性取决于其他属性

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

发布评论

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

>www.elefans.com

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