Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I determine if a value matches a type alias?

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?

like image 1000
Peter Avatar asked Oct 24 '25 00:10

Peter


2 Answers

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

like image 195
Titian Cernicova-Dragomir Avatar answered Oct 26 '25 22:10

Titian Cernicova-Dragomir


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.

  1. it imposes no overhead
  2. preserves runtime behavior of javascript
  3. and does not provide additional runtime functionality

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.

like image 23
user1817787 Avatar answered Oct 27 '25 00:10

user1817787