linkedlist:

Type Guards using Property Access in TypeScript

#23 · · TypeScript

Union types in TypeScript are very useful. But whenever you need to find out what type exactly you are dealing with, it gets slightly annoying. You can't just check whether some property exists or not. Instead, you need to use some kind of type narrowing or type guard. There is a feature request to Consider property access a form of type guards, though.

type Foo = {prop: object};
type Bar = {};

const val: Foo | Bar = getFooOrBar();

// both of these fail with
// "Property 'prop' does not exist on type 'Foo | Bar'.(2339)"
if (val.prop) {}
if (val.prop !== undefined) {}

// all of these work
if ('prop' in val) {}
if ((val as Foo).prop !== undefined) {}
if (isFoo(val)) {}

function isFoo(val: Foo | Bar): val is Foo {
  return (val as Foo).prop !== undefined;
}