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?
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');
}
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