假设我们有以下 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 接口可选属性取决于其他属性
发布评论