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;
}