Typescript: check if value is contained in type

后端 未结 4 1581
既然无缘
既然无缘 2020-12-19 01:34

I have problem with defined types and checking if a value is contained in that type.

Here is my example:

these are the types:

export type Key         


        
4条回答
  •  渐次进展
    2020-12-19 01:52

    If you check that the strings are the exact strings of the type, or if you check that they are not the strings that are not in the Key type it will work:

    export type Key = 'features' | 'special';
    
    export type TabTypes = 'info' | 'features' | 'special' | 'stars';
    function activeTabChanged(event: TabTypes) {
        var activeTab: TabTypes = event;
        if(event != 'info' && event != 'stars') {
            let key: Key = event;
        }
        // OR
        if(event == 'features' || event == 'special') {
            let key: Key = event;
        }
    }
    

    Edit

    The problem with the type definition is that it is erased at compile time, so at runtime there is no way to perform the check. A more verbose way of declaring the enum base on this page and a type guard can help acieve the effect:

    /** Utility function to create a K:V from a list of strings */
    function strEnum(o: Array): {[K in T]: K} {
        return o.reduce((res, key) => {
        res[key] = key;
        return res;
        }, Object.create(null));
    }
    const Key = strEnum([
        'features',
        'special',
    ])
    type Key = keyof typeof Key;
    function isKey(key: string) : key is Key {
        return Key[key] !== undefined;
    }
    
    export type TabTypes = 'info' | 'features' | 'special' | 'stars';
    
    
    function activeTabChanged(event: TabTypes) {
        var activeTab: TabTypes = event;
        if(isKey(event)) {
            let key: Key = event;
        }
    }
    

    This example is worth it if the enums are large, otherwise the first version might work just as well.

提交回复
热议问题