[英]Require type A is a string in type B array in Typescript
I have a type that looks like this:我有一个看起来像这样的类型:
type MyType = {
tabs: string[];
activeTab: string;
}
I want to require that activeTab
is a member of tabs
.我想要求
activeTab
是tabs
的成员。 Is there a way to do this with generics?有没有办法用 generics 做到这一点?
Sure can.当然可以。 Just accept a generic parameter that is a union of all possible strings.
只需接受一个通用参数,它是所有可能字符串的联合。
type MyType<Tab extends string> = {
tabs: Tab[];
activeTab: Tab;
}
const a: MyType<'asd' | 'qwe'> = {
tabs: ['asd', 'qwe'],
activeTab: 'asd'
}
const b: MyType<'asd' | 'qwe'> = {
tabs: ['asd', 'qwe'],
activeTab: 'nope' // Type '"nope"' is not assignable to type '"asd" | "qwe"'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.