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?
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');
}
type Foo will not be compiled into the generated javascript. It can not be realized in an elegant way. As one option: use an array with the specified strings, or get at these fields through an enum.