Let's say we have the following typescript interface:
假设我们有以下打字稿界面:
interface Sample {
key1: boolean;
key2?: string;
key3?: number;
};
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?
在这种情况下,key1始终是必需的,key2始终是可选的,而key3在key1为true时应该存在,如果key1为false则不应该存在。换句话说,密钥的出现取决于另一个密钥的值。我们怎样才能在打字稿中实现这一目标?
1 个解决方案
#1
7
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
}
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).
在这种情况下,类型别名是您正在描述的两种类型的并集。因此,Sample应该是第一个成分(其中key1为true且key3是必需的)或第二个成分(其中key1为false且key3不存在)。
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!
希望有所帮助。祝你好运!
#1
7
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
}
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).
在这种情况下,类型别名是您正在描述的两种类型的并集。因此,Sample应该是第一个成分(其中key1为true且key3是必需的)或第二个成分(其中key1为false且key3不存在)。
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!
希望有所帮助。祝你好运!