Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 3.4Literal, union and unknown types

Types can describe a small set of allowed values rather than every possible string or number.

Union types

TypeScript
type Status = "idle" | "loading" | "complete";
let status: Status = "idle";

A union uses |. It is a better model than a broad string when only selected states are valid.

Narrowing

When a value can have several types, TypeScript needs evidence before allowing an operation that works on only one of them.

TypeScript
function display(value: string | number) {
  if (typeof value === "string") {
    return value.toUpperCase();
  }
  return value.toFixed(2);
}
Feedback 👍
Comments are sent via email to me.