← All tips

TypeScript: narrow with `in` operator

typescripttyping

Use 'prop' in obj to narrow union types.

type A = { a: number } | { b: string };
function f(x: A) {
  if ('a' in x) return x.a;
  return x.b;
}