I need a TypeScript function to test if an object is of a specific type. If so, the method should return this type. If not the method should return undefined. I want to use this function in the following way:
const mySpecialObject = isSpecialObject(source);
if (mySpecialObject) {
console.log(mySpecialObject.getSpecialProperty());
}
I tried to export a function like this one:
export function isSpecialObject(element: SomeBaseObject): SpecialObject {
if (element instanceof SpecialObject) {
return element;
}
return undefined;
}
But the compiler claimed that 'undefined' is not assignable of Type SpecialObject
How should a TypeScript function with this behavior look?
You want a type predicate function to make this thing safer!
export function isSpecialObject(element: SomeBaseObject): element is SpecialObject {
return element instanceof SpecialObject;
}
if (isSpecialObject(element)) {
// element is safe to use as SpecialObject
}
It's also possible to use a type predicate function for multiple types like this:
export function isSpecialObject(element: SomeBaseObject): element is SpecialObject | SpecialObjectSub1 | SpecialObjectSub2 {
return element instanceof SpecialObject || element instanceof SpecialObjectSub1 || element instanceof SpecialObjectSub2;
}
Since the two possible outcome to be returned by the function are SpecialObject or undefined, so undefined can be added as a possible returned type. as below
export function isSpecialObject(element: SomeBaseObject): SpecialObject | undefined {
if (element instanceof SpecialObject) {
return element;
}
return undefined;
}