【问题标题】:Typescript: check if value is contained in type打字稿:检查值是否包含在类型中
【发布时间】:2018-05-14 08:39:12
【问题描述】:

我在定义类型和检查该类型中是否包含值时遇到问题。

这是我的例子:

这些是类型:

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 types


    【解决方案1】:

    你可以使用字符串枚举。

    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'); }
    

    【讨论】:

    • currentKey in Keys 不适用于字符串枚举,只能用于数字枚举
    【解决方案2】:

    这个answer 对类似问题可能有用。它并不能完全回答您的问题,但它显示了实现所需结果的类似方法。

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

    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;
        }
    }
    

    【讨论】:

      【解决方案3】:

      2019年解决方案:

      我有同样的需求,并在另一个线程中找到了一种更简单的方法。总而言之,Patrick Roberts 在该链接中所说的(使用此问题值更新)是:

      不要过于复杂。

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

      请参阅What does the `is` keyword do in typescript?,了解有关我们为什么不只使用boolean 返回类型的更多信息。

      致谢和完整来源:https://stackoverflow.com/a/57065680/6080254

      【讨论】:

        猜你喜欢
        • 2021-09-26
        • 1970-01-01
        • 2019-05-26
        • 1970-01-01
        • 2018-11-03
        • 1970-01-01
        • 2020-12-24
        • 2022-01-20
        • 1970-01-01
        相关资源
        最近更新 更多