Non-unit types as union discriminants

TypeScript 3.2 makes narrowing easier by relaxing rules for what it considers a discriminant property.Common properties of unions are now considered discriminants as long as they contain some singleton type (e.g. a string literal, null, or undefined), and they contain no generics.

As a result, TypeScript 3.2 considers the error property in the following example to be a discriminant, whereas before it wouldn’t since Error isn’t a singleton type.Thanks to this, narrowing works correctly in the body of the unwrap function.

  1. type Result<T> =
  2. | { error: Error; data: null }
  3. | { error: null; data: T };
  4. function unwrap<T>(result: Result<T>) {
  5. if (result.error) {
  6. // Here 'error' is non-null
  7. throw result.error;
  8. }
  9. // Now 'data' is non-null
  10. return result.data;
  11. }