TExcelTAD
Home › TypeScript › TS Union Types

TypeScript Union Types

Real data is rarely just one shape. An ID might arrive as a number from your database but as a string from a URL; a function might return a result or nothing. A union type describes a value that can be one of several types. You write it by joining the types with a vertical bar |, which you can read as "or".

ts · try it yourself
let id: number | string;

id = 42;
console.log(id);

id = "A-42";
console.log(id);
42
A-42

Unions catch the wrong type

A union is still a restriction: anything that is not one of the listed members is rejected.

ts · try it yourself
let id: number | string = 7;
id = true;
main.ts(2,1): error TS2322: Type 'boolean' is not assignable to type 'string | number'.

Notice that TypeScript prints the union as string | number — the order of members does not matter, A | B is exactly the same type as B | A.

You can only use what all members share

When a value has a union type, TypeScript only lets you use operations that are valid for every member. Strings have .toUpperCase(), numbers do not, so calling it directly is an error:

ts · try it yourself
function shout(value: string | number) {
  return value.toUpperCase();
}
console.log(shout("hi"));
main.ts(2,16): error TS2339: Property 'toUpperCase' does not exist on type 'string | number'.
  Property 'toUpperCase' does not exist on type 'number'.

The error message even tells you which member is missing the property. Methods that exist on both, such as .toString(), are fine without any checks.

Narrowing a union

To use member-specific features, first check which member you have. Inside an if (typeof value === "string") block, TypeScript narrows the type to string; in the else branch only number is left. This is called narrowing and it is covered in depth in the Narrowing & Type Guards lesson.

ts · try it yourself
function shout(value: string | number): string {
  if (typeof value === "string") {
    return value.toUpperCase();      // value: string here
  }
  return value.toFixed(1);           // value: number here
}

console.log(shout("hi"));
console.log(shout(3));
console.log([1, "two", 3.5].map((v) => v.toString()));
HI
3.0
[ '1', 'two', '3.5' ]

Unions of arrays vs. arrays of unions

Brackets matter. Compare these two:

Type Means Valid value
(string | number)[] one array whose items may be mixed [1, "a", 2]
string[] | number[] either an all-string array or an all-number array ["a", "b"] or [1, 2]
ts · try it yourself
const mixed: (string | number)[] = [1, "a", 2];
const pure: string[] | number[] = [1, 2, 3];

console.log(mixed.length, pure.length);
3 3

Unions with literal values

Unions are not limited to big types like string. You can list exact values, which gives you a lightweight alternative to enums:

ts · try it yourself
type Size = "small" | "medium" | "large";

function price(size: Size): number {
  if (size === "small") return 2;
  if (size === "medium") return 3;
  return 4;
}

console.log(price("medium"));
console.log(price("large"));
3
4

Calling price("huge") would be a compile error, so a typo in a size name never reaches your users. You will see much more of this in the Literal Types lesson.

Tip: A very common union is T | undefined or T | null, meaning "a T or nothing". The Null & Undefined lesson shows how strict mode makes you handle the "nothing" case.

Test yourself

Which type allows a value to be either a string or a number?

  1. string & number
  2. string | number
  3. string, number
  4. [string, number]

Given let v: string | number, why is v.toUpperCase() an error?

  1. Unions can't have methods
  2. toUpperCase doesn't exist on number, one of the members
  3. Strings are immutable
  4. You must cast with as any first

What does string[] | number[] describe?

  1. An array mixing strings and numbers
  2. Either an array of only strings or an array of only numbers
  3. A tuple of a string and a number
  4. A string or a number