anijap anijap - 1 month ago 16
TypeScript Question

Check if variable is a specific interface type in a typescript union

Is it possible to create a typeguard, or something else that accomplishes the same purpose, to check if a variable is a specific interface type in a typescript union?

interface Foo { a:string }
interface Bar { b:string }

(function() {
function doStuff(thing: Foo | Bar) {
if(typeof thing === 'Foo') {
console.log('Foo');
}
else if (typeof thing === 'Bar') {
console.log('Bar');
}
else {
console.log('unknown');
}
}

var thing: Foo = {a:'a'};
doStuff(thing);
})();

Answer

typeof doesn't do this. It always return "string", "number", "boolean", "object", "function", or "undefined".

You can test for object properties with a test like if(thing.a !== undefined) { or if(thing.hasOwnProperty('a')) {.

Note that you could make an object that had both a string a and a string b, so be aware of that possibility.