Can I check a type against a union type in typescript?
If you knew some specific key for an interested Type you can do it via in
operator:
function move(pet: Fish | Bird) {
if ("swim" in pet) {
return pet.swim(); //pet is Fish
}
return pet.fly(); //pet is Bird
}
As for me much easier than an additional function with stuff. That what I was looking for.
Docs.
There's no runtime representation of type aliases, so there's nothing "built in" per se for doing this kind of check.
This pattern would be fairly maintainable, though:
// Future devs: Please keep these in sync
type MyType = Foo|Bar|Thing;
let MyTypeClasses = [Foo,Bar,Thing];
function getMyType(): MyType {
var item = getBase();
if (MyTypeClasses.some(c => item instanceof c))
return item;
else
return null;
}
Typescript has introduced some new features that make this easier since the accepted answer was published. Here's now I would do this in 2020 as of Typescript 3.8.3:
const myTypes = ['Foo', 'Bar', 'Thing'] as const;
type MyType = typeof myType[number]; // 'Foo' | 'Bar' | 'Thing'
// Return a typed MyType if string is valid (else throw).
function getMyType(maybeMyType: string): MyType {
const myType = myTypes.find((validType) => validType === maybeMyType);
if (myType) {
return myType;
}
throw new Error(`String "${maybeMyType}" is not of type MyType.`);
}
// Use it like this:
const definitelyMyType = getMyType('Foo');
Or if you prefer the less-safe-but-arguably-more-readable custom type guard style you could do it like this:
// Define a custom type guard to validate & assert that maybeMyType is MyType.
function isMyType(maybeMyType: string): maybeMyType is MyType {
return myTypes.includes(maybeMyType);
}
// Use it like this:
const maybeMyType = 'Foo';
if (isMyType(maybeMyType)) {
const definitelyMyType: MyType = maybeMyType;
}