Typescript: check if value is contained in type

后端 未结 4 686
青春惊慌失措
青春惊慌失措 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 02:03

    You could use a string enum.

    export enum Keys = {
      Features = 'features',
      Special = 'special',
    }
    
    // Compare it
    if (currentKey === Keys.Special) { console.log('Special key is set'); }
    

    In order to check if your value is defined in the predefined Enum at all you can do:

    if (currentKey in Keys) { console.log('valid key'); }
    

提交回复
热议问题