Typescript从同一接口支柱创建动力联合类型
我想从同一界面的兄弟创建联合类型,
如下
interface Foo {
values: string[];
defaultValue: string;
}
function fooo({values, defaultValue}: Foo) {}
fooo({values: ['a', 'b'], defaultValue: 'a'}); // this is correct example
fooo({values: ['a', 'b'], defaultValue: 'c'}); // I want to prevent this case!
// defaultValue must be 'a' or 'b'
// like tuple type 'a' | 'b'
所示吗?
I want to create union type from brother of same interface
like below
interface Foo {
values: string[];
defaultValue: string;
}
function fooo({values, defaultValue}: Foo) {}
fooo({values: ['a', 'b'], defaultValue: 'a'}); // this is correct example
fooo({values: ['a', 'b'], defaultValue: 'c'}); // I want to prevent this case!
// defaultValue must be 'a' or 'b'
// like tuple type 'a' | 'b'
Can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当然,您可以通过添加通用类型来实现这一目标。
通用类型
k
将value
数组的元组类型。然后,我们将defaultValue
限制为仅在values
中指定的值k [number]
。让我们看看它是否有效:
游乐场
Sure, you can achieve this by adding generic types.
The generic type
K
will the tuple type of thevalue
array. We then constraindefaultValue
to only have the values specified invalues
withK[number]
.Let's see if it works:
Playground