Typescript: check if value is contained in type

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

    2019 Solution:

    I had the same need and found an easier way to do that in another thread. In summary, what Patrick Roberts says in that link (updated with this question values) is:

    Don't over-complicate it.

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

    See What does the `is` keyword do in typescript? for more information on why we don't just use a boolean return type.

    Credits and full source here: https://stackoverflow.com/a/57065680/6080254

提交回复
热议问题