joshp
joshp

Reputation: 826

Check if string exists in union type

If I have the following type:

type foo = 'bar' | 'baz';
const test = 'bit';

How do I check if test is a member of foo?

(is it really so crazy hard to do as this: UnionToTuple)

Upvotes: 1

Views: 3379

Answers (2)

You can just use function for validation:

type Foo = 'bar' | 'baz';
const test = 'bit';

const isFoo=(a:Foo)=>a
isFoo(test) // error
isFoo('bar') // ok

Upvotes: 1

Louis Weng
Louis Weng

Reputation: 61

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

Upvotes: 2

Related Questions