打字稿:检查类型中是否包含值

san*_*ooh 5 types typescript angular

我对定义的类型有疑问,并检查该类型中是否包含值。

这是我的示例:

这些类型是:

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

export type TabTypes = 'info' | 'features' | 'special' | 'stars';
Run Code Online (Sandbox Code Playgroud)

当用户更改选项卡时,它会从Type of 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;
}
Run Code Online (Sandbox Code Playgroud)

有没有一种打字稿方法来检查带有类型的发送值是否可以等于来自其他类型的值?

Bru*_*iro 15

2019年解决方案:

我有同样的需求,并在另一个线程中找到了一种更简单的方法。总之,帕特里克罗伯茨在该链接中所说的(用这个问题值更新)是:

不要把它复杂化。

function isOfTypeTabs (keyInput: string): keyInput is TabTypes {
  return ['info', 'features', 'special', 'stars'].includes(keyInput);
}
Run Code Online (Sandbox Code Playgroud)

请参阅打字稿中的“is”关键字有什么作用?有关为什么我们不只使用boolean返回类型的更多信息。

积分和完整来源:https : //stackoverflow.com/a/57065680/6080254


ken*_*tor 6

您可以使用字符串枚举。

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

// Compare it
if (currentKey === Keys.Special) { console.log('Special key is set'); }
Run Code Online (Sandbox Code Playgroud)

为了检查您的值是否在预定义的枚举中定义,您可以执行以下操作:

if (currentKey in Keys) { console.log('valid key'); }
Run Code Online (Sandbox Code Playgroud)

  • 正如 @MaorRefaeli 上面所说,使用 `currentKey in Keys` 根本不起作用。这怎么得到赞成票是很奇怪的,因为如果你尝试这样做,它就不会起作用。我花了 15 分钟重构我的代码,结果当我运行我的代码时它不起作用。 (2认同)