Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: check if value is contained in type

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 = 'features' | 'special';

export type TabTypes = 'info' | 'features' | 'special' | 'stars';

when the user changes a tab, it sends a string value from Type of 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;
}

is there a typescript way to check if a sent value with a type can equal a value from a different type?

like image 270
sanyooh Avatar asked Nov 30 '17 12:11

sanyooh


2 Answers

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

like image 188
Bruno Monteiro Avatar answered Oct 18 '22 07:10

Bruno Monteiro


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'); }
like image 34
kentor Avatar answered Oct 18 '22 08:10

kentor