AI Hints
Home›TypeScript Tutorial›Cart Practice and Unions
TypeScript · Lesson 30 of 120

Union Types

This or that.

⏱ 2 min read▶ Video at 23:48🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Sometimes a value can be one of several types. An order ID might be a number, or a string like NW ten forty two. A union type, written with a vertical bar, allows either.

Union Types
From the video: Union Types
  • One of several types
  • Number or string
  • A vertical bar

A union

Order ref can be a number or a string. Both calls are allowed. Inside the function, we can only use what both types share, like printing. Run it.

app.tstypescript
function show(orderRef: number | string) {
  console.log("Order:", orderRef);
}

show(1042);
show("NW-1042");
Output
Order: 1042
Order: NW-1042

Only shared methods

Here we call upper case on the union. Run it. Numbers don't have that method, so TypeScript refuses, until we check which type it is.

app.tstypescript
function shout(orderRef: number | string) {
  return orderRef.toUpperCase();
}
Output
app.ts line 2: Property 'toUpperCase' does not exist on type 'string | number'.
  Property 'toUpperCase' does not exist on type 'number'.

Summary

A union allows several types, but you must check which one you have before using type specific methods. Next, narrowing with typeof.

Key takeaways
  • number | string
  • Either works
  • Check before use
Next up: Narrowing with typeof — check, then use