简体   繁体   English

要求 A 类型是 Typescript 中 B 类型数组中的字符串

[英]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 .我想要求activeTabtabs的成员。 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"'
}

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM