Typescript: check if value is contained in type

后端 未结 4 679
青春惊慌失措
青春惊慌失措 2020-12-19 01:08

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:51

    This answer to a similar question might be useful. it doesn't exactly answer your question, but it shows a similar way to achieve the desired result.

    In short, you can use array for inclusion checks, and type for type safety:

    const keys =  ['features','special'];
    export type Key = typeof keys[number];
    const tabTypes =  ['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;
        }
    }
    

提交回复
热议问题