Typescript:检查类型中是否包含值

Typescript:检查类型中是否包含值,typescript,types,Typescript,Types,我对定义的类型和检查该类型中是否包含值有问题 以下是我的例子: 这些类型包括: export type Key = 'features' | 'special'; export type TabTypes = 'info' | 'features' | 'special' | 'stars'; 当用户更改选项卡时,它会从TabTypes类型发送一个字符串值 activeTabChanged(event: TabTypes) { this.activeTab: TabTypes = e

我对定义的类型和检查该类型中是否包含值有问题

以下是我的例子:

这些类型包括:

export type Key = 'features' | 'special';

export type TabTypes = 'info' | 'features' | 'special' | 'stars';
当用户更改选项卡时,它会从TabTypes类型发送一个字符串值

activeTabChanged(event: TabTypes) {
    this.activeTab: TabTypes = event;
    // it won't let me set the key here because key has a different type 
    // but the send event can be contained in type Key
    // how can I check if the send event from type TabTypes is contained in type Key
    this.key: Key = event;
}

是否有一种typescript方法来检查发送的类型值是否与其他类型的值相等?

您可以使用字符串枚举

export enum Keys = {
  Features = 'features',
  Special = 'special',
}

// Compare it
if (currentKey === Keys.Special) { console.log('Special key is set'); }
为了检查您的值是否在预定义枚举中定义,您可以执行以下操作:

if (currentKey in Keys) { console.log('valid key'); }
这对于类似的问题可能是有用的。它并没有完全回答你的问题,但它显示了一种类似的方式来达到预期的结果

简而言之,您可以使用数组进行包含检查,使用类型进行类型安全检查:

const keys = <const> ['features','special'];
export type Key = typeof keys[number];
const tabTypes = <const> ['info' ,'features' ,'special', 'stars'];
export type TabTypes = typeof tabTypes[number];

activeTabChanged(event: TabTypes) {
    this.activeTab: TabTypes = event;
    // it won't let me set the key here because key has a different type 
    // but the send event can be contained in type Key
    // how can I check if the send event from type TabTypes is contained in type Key

    if (event in keys) {
        this.key: Key = event as Key;
    }
}
const key=['features','special'];
导出类型键=键的类型[编号];
const tabTypes=['info','features','special','stars'];
导出类型TabTypes=TabTypes的类型[编号];
activeTabChanged(事件:TabTypes){
this.activeTab:TabTypes=event;
//它不允许我在这里设置键,因为键的类型不同
//但是发送事件可以包含在类型Key中
//如何检查类型键中是否包含TabTypes类型的发送事件
if(事件在键中){
this.key:key=事件作为key;
}
}
2019解决方案: 我也有同样的需求,并在另一个线程中找到了一种更简单的方法。总之,Patrick Roberts在该链接(更新了此问题值)中说:

别把它复杂化了

有关为什么不使用
boolean
返回类型的更多信息,请参阅


此处的积分和完整源代码:

currentKey-in-Keys
不适用于字符串枚举,仅适用于数字枚举当前在@MaorRefaeli下有效
function isOfTypeTabs (keyInput: string): keyInput is TabTypes {
  return ['info', 'features', 'special', 'stars'].includes(keyInput);
}