unknown Absorbs Unions never Erases Them

unknown swallows any union it joins while never vanishes from unions and erases intersections — the two bottom types pull in opposite directions.

TypescriptData Integrity

Code

typescriptsnippet
36 lines
// unknown absorbs unions: string | unknown collapses to unknown
type Widened = string | unknown; // unknown

// never vanishes from unions and erases intersections
type KeptA = string | never; // string
type KeptB = string & unknown; // string
type Erased = string & never; // never

declare function assertNever(value: never): void;

type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'square'; side: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case 'circle':
      return Math.PI * shape.radius ** 2;
    case 'square':
      return shape.side ** 2;
    default: {
      // shape is narrowed to never here; adding a variant breaks this line
      const exhausted: never = shape;
      assertNever(exhausted);
      return exhausted;
    }
  }
}

console.log(area({ kind: 'circle', radius: 2 }).toFixed(2));
console.log(area({ kind: 'square', side: 3 }));

// unknown accepts any initializer; KeptA stays string-only
const widened: Widened = 42;
const keptA: KeptA = 'still a string';
console.log(widened, keptA, keptA.length);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

12.57
9
42 still a string 14

How the snippet works

The snippet is organized around the functions assertNever and area.

Points of care

  • The project needs no additions before running it.

Using it

The one signature that matters here is function assertNever(value: never)

Key statements

return Math.PI * shape.radius ** 2;
return shape.side ** 2;

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. The file defines `assertNever`, `area` at load time.