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?
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
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'); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With