In TypeScript, can I determine if a value is/matches a type alias?
Say I have this type:
export type Name = "Jane" | "John";
Then somewhere else I want to check if a certain piece of user input is of the Name type. Something like if (input instanceOf Name) won't work.
Is this even possible?
You can't check if a value matches a type alias. Types are erased at runtime, so any runtime code can't ever depend on them.
If you control the type alias I would recommend creating an array to hold the values, let TS infer the type for it, and derive the union from it. You can then check if a value is in the array:
const Name = ["Jane", "John"] as const
export type Name = typeof Name[number];
function isName(a: unknown): a is Name {
return Name.indexOf(a as Name) != -1;
}
Playground Link
The only way that I am aware so far is generating the type alias from a const array, then checking your name against this array.
const names = ["Jane", "John"] as const;
type Name = typeof names[number];
function isValidName(name: string): name is Name {
return names.includes(<Name> name);
}
Usage:
const test: string = "John";
if (isValidName(test)) {
console.log(`${test} is a name`);
}
else {
console.log(`${test} is not a name`);
}
I still can't understand why typescript can't compile from something like
type Example = 'first' | 'second';
const exampleValues = [typeof Example] as const;
to
const exampleValues = ['first', 'second'];
the answer AFAIK is that "Types are erased at runtime", but compiling a type alias to a literal array does not require type information during runtime.
this would allow for developers to validate a string at runtime by looking for a value inside the array.
If there is a way to accomplish this please let me know. As I showed you can do the opposite, from an array to a type alias, but with type alias you can filter and combine types, and I am interested in converting from a type alias to an array at compile time.
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