4

In this Q/A, I have seen a union type definition wrapped into square brackets (edit: the question has been fixed by now). So far, I've only seen union types without square brackets. What is the difference between e.g.:

type UnionA = number | string;
type UnionB = [number | string];

I'm aware of the following meaning of square brackets in TS:

bluenote10
  • 23,414
  • 14
  • 122
  • 178

1 Answers1

6

I've missed a basic type of TypeScript: Tuples.

So the semantics of UnionA and UnionB are different:

let x: UnionA = 0      // works
let x: UnionA = ""     // works
let x: UnionB = 0      // doesn't work
let x: UnionB = ""     // doesn't work
let x: UnionB = [0]    // works
let x: UnionB = [""]   // works

Basically UnionB is a tuple of length 1 with its first element being a union of number | string.

In retrospect, the linked question most likely

  • didn't mean to use [] to get the plain union type, or
  • was intended to use , instead of | to get a meaningful tuple with multiple fields.
bluenote10
  • 23,414
  • 14
  • 122
  • 178