Discriminated unions

A discriminated union is a type that holds one of several classes or interfaces, and a tag that says which. In Nish each variant records its tag in its first field, a readonly field of an enum member type, and the union reads that tag. The normative rules are in the reference's Discriminated unions section.

enum Kind {
  Circle,
  Square,
}

class Circle {
  readonly kind: Kind.Circle = Kind.Circle;
  r: i32 = 3;
}

class Square {
  readonly kind: Kind.Square = Kind.Square;
  side: i32 = 4;
}

type Shape = Circle | Square;

const pick = (round: boolean): Shape => (round ? new Circle() : new Square());

const name = (s: Shape): string => (s.kind === Kind.Circle ? "circle" : "square");

export const main = (): i32 => {
  const shapes: Shape[] = [pick(true), new Square()];
  for (const s of shapes) {
    console.log(name(s)); // circle, then square
  }
  return 0;
};

What makes a variant

Every variant is a class or an interface that is not generic, and its first field is its tag: a field whose type is one member of an enum. All the variants of one union take their tags from the same enum, give the tag the same name, and have different tags, so the tag tells them apart. A union names at least two different variants.

A class without such a field is not a variant:

class Point {
  x: i32 = 0;
}

class Line {
  length: i32 = 0;
}

type Thing = Point | Line;

The tag's type is the one member, readonly kind: Kind.Circle = Kind.Circle, not the whole enum: readonly kind: Kind = Kind.Circle is an error (NL2559), because every variant would then share that type and a test of it could not tell them apart.

The tag is readonly, so a variant keeps the tag it was built with. A class that implements an interface variant is not a variant itself: convert it to the interface first, const r: Ring = new Band().

Any other union, such as i32 | string, is refused, as before. T | null still works, and so does Shape | null.

Where a union goes

A union is the type of a local, a parameter, a field, a return value, an array element or a Map's value, and Shape | null of any of those. An alias may name another union: with type Round = Circle | Square, type Shape = Round | Tri holds all three. A variant converts into it wherever one is expected: a new Circle() passed to a Shape parameter, returned from a function that answers Shape, or written into a Shape[] literal; so does a Round where a Shape is wanted.

A union crosses modules like any exported type, but not a C header or a N-API bridge: a sidecar has no C spelling for it yet, so an exported signature that holds one is refused. So is a field that holds one, in any class or interface of the program, exported or not: a header lays out every class, a private one too.

Map<string, Shape> holds its values as they are, as an array does, and its get answers Shape | undefined. A union is also a type argument: a generic class over it, Box<Shape> or Stack<Shape>, holds the union in each T slot, a generic function called with one binds its type parameter to the union, and a Result can carry one on either side. A variant converts here too, so new Box<Shape>(new Circle()) and Ok(new Square()) need no cast:

enum Kind {
  Circle,
  Square,
}

class Circle {
  readonly kind: Kind.Circle = Kind.Circle;
  r: i32;
  constructor(r: i32) {
    this.r = r;
  }
}

class Square {
  readonly kind: Kind.Square = Kind.Square;
  side: i32;
  constructor(side: i32) {
    this.side = side;
  }
}

type Shape = Circle | Square;

class Box<T> {
  value: T;
  constructor(value: T) {
    this.value = value;
  }
}

const area = (s: Shape): i32 => {
  switch (s.kind) {
    case Kind.Circle:
      return 3 * s.r * s.r;
    case Kind.Square:
      return s.side * s.side;
  }
};

const largest = <T>(xs: T[], measure: (x: T) => i32): T => {
  let best = xs[0];
  for (const x of xs) {
    if (measure(x) > measure(best)) {
      best = x;
    }
  }
  return best;
};

export const main = (): void => {
  const b = new Box<Shape>(new Circle(2));
  const shapes: Shape[] = [new Square(3), b.value, new Square(4)];
  console.log(area(largest(shapes, area)));
};

A store of a bare variant into a generic instance's union field, b.value = new Square(1), is refused as into any union field (Declare what you store). A union does not meet a constraint such as <T extends HasKind>, and an instance over a union is not a class typed JSON writes. And a union is still not a Set element or a Map key:

enum Kind {
  Circle,
  Square,
}

class Circle {
  readonly kind: Kind.Circle = Kind.Circle;
}

class Square {
  readonly kind: Kind.Square = Kind.Square;
}

type Shape = Circle | Square;

export const main = (): void => {
  const seen = new Set<Shape>();
  console.log(seen.size);
};

Reading the tag

Through the union itself, the tag is the one member you can read. s.kind reads it, and it compares, switches and passes as the enum. Any other field or method of a variant is an error until a test of the tag says which variant s is, and so is writing to the union's fields, even one every variant has.

enum Kind {
  Circle,
  Square,
}

class Circle {
  readonly kind: Kind.Circle = Kind.Circle;
  r: i32 = 3;
}

class Square {
  readonly kind: Kind.Square = Kind.Square;
  r: i32 = 4;
}

type Shape = Circle | Square;

const radius = (s: Shape): i32 => s.r;

Give the tag a type when you store it, const k: Kind = s.kind. TypeScript would infer the union of the variants' tags, Kind.Circle | Kind.Square, which is not a type Nish has in this version.

Narrowing by the tag

A test of the tag narrows the union, as in TypeScript. Inside if (s.kind === Kind.Circle) { ... }, s is a Circle, and every field and method of Circle reads through it; in the else, and after an if whose body always leaves with return, break, continue or a panic(...), it is whatever variants remain. !==, the operands the other way round (Kind.Circle === s.kind), a ternary, && and || narrow the same way, and so does each case of a switch (s.kind), with default holding the variants no case named.

enum Kind {
  Circle,
  Square,
}

class Circle {
  readonly kind: Kind.Circle = Kind.Circle;
  r: i32 = 3;
}

class Square {
  readonly kind: Kind.Square = Kind.Square;
  side: i32 = 4;
}

type Shape = Circle | Square;

const area = (s: Shape): i32 => {
  if (s.kind === Kind.Circle) {
    return 3 * s.r * s.r;
  }
  return s.side * s.side;
};

const perimeter = (s: Shape): i32 => {
  switch (s.kind) {
    case Kind.Circle:
      return 6 * s.r;
    default:
      return 4 * s.side;
  }
};

export const main = (): i32 => {
  const shapes: Shape[] = [new Circle(), new Square()];
  let total = 0;
  for (const s of shapes) {
    total = total + area(s) + perimeter(s);
  }
  console.log(total);
  return 0;
};

Where an || held, either side may be the one that held, so the variable is whatever either side proved: inside if (s.kind === Kind.Circle || s.kind === Kind.Square), s is a Circle | Square. That union still has only its tag, but its tag cannot be Kind.Tri, so testing for it there is an error (NL2531). The side of an && where it failed works the same way, and so does an enum variable. A test may also read the variable through an assignment, as in if ((t = next()).kind === Kind.Square), which narrows the t just stored.

An assignment to the variable drops what a test proved, so a read after it needs a new test. Past an if, the variable is what the arms that carry on left it: after an else if chain whose branches all return, s is the variant no test named, and an arm that assigns s leaves what it assigned. A test nested inside the arms counts too: when each arm returns if s.kind === Kind.Circle, s is not a Circle past the if, and the ways out of a switch join the same way.

A narrowing of the union belongs to a variable or a parameter: a test of a.b.kind does not narrow a.b, so a.b.r is an error (NL2558) — copy it into a const and test that. The tag read through the path does stay narrowed, as in TypeScript, so a second a.b.kind === Kind.Circle after the first ruled it out is an error, until a store to a.b, a.b.kind or a.

An index belongs to the path when it names one element, as in TypeScript: a number, a parameter, a const (after const i = 0, xs[i] is xs[0], and so is xs[j] after const j = i), a module constant (after const IDX: i32 = 0, xs[IDX] is xs[0] too), or a let that nothing assigns. Through a loop counter, which i++ assigns, xs[i] is not narrowed, and a store xs[j] = t through it clears nothing. And where TypeScript would type a value never, because every tag has been tested away, reading it is an error (NL2557).

A comparison the tests above it have already ruled out is an error, as in TypeScript: after if (s.kind === Kind.Circle) { return 1; }, a second s.kind === Kind.Circle can never be true. So is one against a tag stored in const k: Kind = s.kind that no variant has, because the local holds only the variants' members.

Any variable of an enum type narrows the same way, a parameter k: Kind as much as that tag local: a test of k === Kind.Circle or k !== Kind.Circle, in every form above and in a switch (k), leaves k holding only the members the test allows, so a second test it already decided is an error (NL2531).

enum Kind {
  Circle,
  Square,
  Tri,
}

const sides = (k: Kind): i32 => {
  if (k === Kind.Circle) {
    return 0;
  }
  return k === Kind.Circle ? 1 : 4;
};

Narrowed to one member, the variable has that member's type, so let j = k is a Kind.Square. Narrowed to several, const j = k needs its annotation, const j: Kind = k, for the reason the tag does (NL2530). And s.kind === k, with k holding Kind.Circle | Kind.Square, makes s a Circle | Square where they are equal; where they differ, nothing is known.

A local that an if, a ternary, a loop or a switch stores members into holds, after it, what it held before or any member stored, so a comparison with a member it cannot hold is an error there too (NL2531). After a switch, that is what each way out of it left: each break, the end of its last clause, and, with no default, the value no case matched.

After a loop, the local holds what TypeScript says it holds: what the loop's head can see, from before the loop, from the end of each iteration and from each continue, with the condition false, together with what each break left. A narrowing made inside the body, by a test or a store, carries to the comparisons after the loop the same way, for a local the loop only tests as much as for one it stores into:

enum Kind {
  A,
  B,
  C,
}

const settled = (n: i32): boolean => {
  let j: Kind = Kind.A;
  let i = 0;
  while (i < n) {
    j = Kind.B;
    j = Kind.C;
    i++;
  }
  return j === Kind.B; // `j` is `Kind.A | Kind.C` here
};

A loop that holds any of these is read more loosely:

  • a field path such as h.k;
  • an assignment written inside another expression (an argument, an initializer, the inner = of k = j = Kind.C);
  • a store of a field or method call read through an array element, a call's result or an object the loop itself creates (gs[0].b);
  • a store of a let the loop declares or of a const it copies from another enum local (the const t = a of a swap);
  • a ternary arm that reads the local where the condition leaves it nothing (k = k === Kind.A ? Kind.B : k);
  • or a type of more than 29 members.

There the local holds every member the body stores anywhere, or the whole enum, so a few comparisons TypeScript refuses still compile.

The language reference lists these shapes under "Accepted here, refused by tsc".

A comparison that can never be true is an error, as in TypeScript: s.kind === Kind.Tri when no variant has the tag Kind.Tri, or a case Kind.Tri: in a switch (s.kind).

Declare what you store

TypeScript narrows a union-typed variable to the type of the value it was last given: after let s: Shape = new Circle(), it treats s as a Circle. This version does not track that, so it refuses a store that would narrow, and asks for one of two things instead: declare the variable as the variant, or give it a value of the whole union, such as a call that returns Shape.

enum Kind {
  Circle,
  Square,
}

class Circle {
  readonly kind: Kind.Circle = Kind.Circle;
}

class Square {
  readonly kind: Kind.Square = Kind.Square;
}

type Shape = Circle | Square;

export const main = (): i32 => {
  const s: Shape = new Circle();
  return s.kind === Kind.Circle ? 0 : 1;
};

A switch that covers every variant

A switch (s.kind) whose case labels name every variant, with no default, is complete: no other value can reach its end. When every clause returns, the function needs no return after it, as in TypeScript, and the compiler marks the case no label names unreachable rather than testing for it. The tag may be read through a variable, a field or an element: s.kind, h.shape.kind, shapes[i].kind.

enum Kind {
  Circle,
  Square,
  Tri,
}

class Circle {
  readonly kind: Kind.Circle = Kind.Circle;
  r: i32 = 3;
}

class Square {
  readonly kind: Kind.Square = Kind.Square;
  side: i32 = 4;
}

interface Tri {
  readonly kind: Kind.Tri;
  base: i32;
}

type Shape = Circle | Square | Tri;

const sides = (s: Shape): i32 => {
  switch (s.kind) {
    case Kind.Circle:
      return 0;
    case Kind.Square:
      return 4;
    case Kind.Tri:
      return 3;
  }
};

Leave a variant out and the function can end without a value, which is an error, as tsc --strict --noImplicitReturns reports it. Adding a variant to the union therefore points at every switch that has to handle it.

enum Kind {
  Circle,
  Square,
  Tri,
}

class Circle {
  readonly kind: Kind.Circle = Kind.Circle;
}

class Square {
  readonly kind: Kind.Square = Kind.Square;
}

interface Tri {
  readonly kind: Kind.Tri;
}

type Shape = Circle | Square | Tri;

const sides = (s: Shape): i32 => {
  switch (s.kind) {
    case Kind.Circle:
      return 0;
    case Kind.Square:
      return 4;
  }
};

A statement after a complete switch whose clauses all return is unreachable code, as it is after an if whose branches both return. A clause that breaks reaches the statement after it, as in TypeScript.

Only a union's own tag makes a switch complete. A switch on a plain enum never is, even with every member named, because a C caller can pass an enum any i32. Nor is one on the tag copied into a local, const k: Kind = s.kind, or on a field's tag that an earlier if narrowed, since a call in between could have replaced the field.

Nor is one on an enum field given a tag, b.k = s.kind: the field is still a Kind, and a call, an alias or a method can store any member in it. What counts is the subject itself, a variant's tag field read on a union value. TypeScript accepts all four. Give such a switch a default, or return after it.

Unions as JSON

A union of classes reads and writes as JSON through nish/json-typed: the tag goes on the wire as the name of its enum member, and jsonDecodeUnion picks the variant by it. When the tags come from a string enum, the tag on the wire is the member's string instead:

import { JsonWriter } from "nish/json";
import { jsonEncode } from "nish/json-typed";

enum Kind {
  Circle = "circle",
  Square = "square",
}

class Circle {
  readonly kind: Kind.Circle = Kind.Circle;
  r: i32 = 3;
}

class Square {
  readonly kind: Kind.Square = Kind.Square;
  side: i32 = 4;
}

type Shape = Circle | Square;

export const main = (): i32 => {
  const shapes: Shape[] = [new Circle(), new Square()];
  for (const s of shapes) {
    const w = new JsonWriter(new Array<u8>(256), 0);
    jsonEncode(w, s);
    console.log(w.text()); // {"kind":"circle","r":3}, then {"kind":"square","side":4}
  }
  return 0;
};

The tag enum can be either kind; nothing else about the union changes. See Tagged unions.