Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check if a string is included in a Union type in TypeScript?

Tags:

typescript

Consider the following code:

type Foo = "Foo" | "Bar" | "Baz"

function isInFoo(str: string) boolean {
    // return Foo.contains(str); ?
}

In typescript, is there an elegant way to check if str is in type Foo?

like image 756
jmrah Avatar asked Oct 31 '22 05:10

jmrah


1 Answers

Type annotations are removed from compiled code and are not available at runtime. But to expand on Ivan's answer, here is an example of extracting typed data from an array:

const fooBar = ['foo', 'bar', 'baz'] as const;
type FooBar = typeof fooBar[number]; // "foo" | "bar" | "baz"

Then you can write a custom type guard that checks a string at runtime:

function isFooBar(string: unknown): string is FooBar {
    return typeof string === 'string' && string in fooBar;
}

And use it like this:

const maybeFooBar: unknown = 'baz';
if (isFooBar(maybeFooBar)) {
    console.log('Typescript knows this is a FooBar');
}
like image 182
jtschoonhoven Avatar answered Nov 15 '22 06:11

jtschoonhoven