I want to check whether str
is in Name
Is it possible?
/* imagination code */
type Name = 'a1' | 'a2' | .... | 'z100';
function isName(str: string): str is Name {
switch (str) {
case 'a1':
case 'a2':
// ...
case 'z100':
return true;
default:
return false;
}
}
isName('alice') // -> true or false
You can't go from a type to a runtime check. Types are erased at compile time so you can't really use any information in them at runtime. You can however go the other way, from a value go to a type:
const Name = ['a1', 'a2', 'z100'] as const // array with all values
type Name = typeof Name[number]; // extract the same type as before
function isName(str: string): str is Name {
return Name.indexOf(str as any) !== -1; // simple check
}
isName('alice') // -> true or false
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