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

Since Typescript 1.6 you can use user-defined type guards:

let isFoo = (object: Foo| Bar): object is Foo => {
    return "a" in object;
}

See https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards and https://github.com/microsoft/TypeScript/issues/10485


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.