A courier brings a parcel. The label says "a book or clothes". Before you open it, you can't put it straight on the bookshelf. Once it's open and it's a book, you know for sure it's a book. And if it isn't a book, what's left must be clothes.
TypeScript does the same with a union value. It's called type narrowing: inside one branch of code, a variable's type is made smaller based on a check you write.
typeof: check a basic type
In the union lesson you used typeof once. Now let's see what TypeScript does on each line:
function getLength(input: string | string[]): number {
if (typeof input === "string") {
return input.length; // input: string
}
return input.length; // input: string[]
}
console.log(getLength("hello")); // 5
console.log(getLength(["a", "b", "c"])); // 3
If you hover over input in the editor, the type shown differs from place to place:
| Where | Type of input |
Why |
|---|---|---|
| start of the function | string | string[] |
no check yet |
inside the if |
string |
typeof input === "string" is true |
after the if |
string[] |
the string branch already did return, so whatever gets here must be an array |
typeofis a JavaScript operator that gives the kind of a value as text:"string","number","boolean","undefined","object","function".- TypeScript follows your
ifandreturn. You don't write a new type; it works it out from the check. .lengthis in both branches, but it means different things: the number of characters ("hello"= 5) and the number of items in the array (["a", "b", "c"]= 3).
Arrays: use Array.isArray
Remember this from the JavaScript lessons? typeof ["a", "b"] gives "object", not "array", because in JavaScript an array is an object. So typeof can't tell an array from any other object. For arrays, use Array.isArray:
function getLength(input: string | string[]): number {
if (Array.isArray(input)) {
return input.length; // input: string[]
}
return input.length; // input: string
}
TypeScript understands Array.isArray too: inside the if, input becomes string[], and after it only string is left.
in and instanceof: check an object
When the union's members are objects, use in or instanceof.
"name" in object checks whether the object has a property with that name:
type Fish = { swim: () => string };
type Cat = { meow: () => string };
function move(animal: Fish | Cat) {
if ("swim" in animal) {
return animal.swim(); // animal: Fish
}
return animal.meow(); // animal: Cat
}
(Fish is a fish that can swim, swim; Cat is a cat that can meow.)
value instanceof Class checks whether the value was made from a class, for example Date:
function getYear(date: string | Date) {
if (date instanceof Date) {
return date.getFullYear(); // date: Date
}
return date; // date: string
}
When one check is used in many places, wrap it in a function with the return type animal is Fish. A function like this is called a type guard:
function isFish(animal: Fish | Cat): animal is Fish {
return "swim" in animal;
}
function move(animal: Fish | Cat) {
if (isFish(animal)) {
return animal.swim(); // animal: Fish
}
return animal.meow(); // animal: Cat
}
animal is Fishmeans: if this function returnstrue,animalis aFish. TypeScript trusts that answer without checking the function's body, so make sure the check is right.- A
nullcheck narrows a type too. Afterif (name === null) return "Hello!",name, which wasstring | null, is onlystring.
Discriminated union: check one telling property
The way you'll see most in real apps: every member of the union has the same property, kind, holding a different literal. That property is called the discriminant.
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Shape = Circle | Square;
function area(b: Shape): number {
if (b.kind === "circle") {
return Math.PI * b.radius * b.radius; // b: Circle
}
if (b.kind === "square") {
return b.side * b.side; // b: Square
}
const check: never = b; // b: never
return check;
}
| Line | Type of b |
|---|---|
| start of the function | Shape |
inside if (b.kind === "circle") |
Circle |
inside if (b.kind === "square") |
Square |
after both ifs |
never |
Once b.kind equals "circle", only Circle fits, so b.radius can be used. b.side in that same branch is rejected, because a circle has no side.
An exhaustive check with never
never is a type with no values at all. After the two ifs, every kind has been handled, so b becomes never and const check: never = b; passes.
Now Triangle is added to the union, but the function area is never updated:
type Triangle = { kind: "triangle"; base: number; height: number };
type Shape = Circle | Square | Triangle;
The line const check: never = b; errors straight away: Type 'Triangle' is not assignable to type 'never'. (ts(2322)). TypeScript points at the kind you haven't handled, before the code ever runs. That's what the never line is for: an alarm for a forgotten branch.
⚠️ Checks that look like they work, but don't
- Using
typeoffor an array. It gives"object". UseArray.isArray(...). - Forgetting
returnin the first branch. If theif (typeof input === "string")branch only doesconsole.logwithoutreturn, then after thatif,inputis stillstring | string[], because both paths reach it. - Checking for a class with
typeof.typeof datefor aDategives"object". Useinstanceof Date. - Thinking the exercise checks your narrowing. In the exercise, a single
return input.length;already gives 5 and 3, because strings and arrays both havelength. Write the check anyway: in real code, the two branches usually do different things.
TL;DR: Type narrowing is TypeScript making a type smaller inside a branch, from a check you write. typeof x === "string" for basic types, Array.isArray(x) for arrays (because typeof of an array is "object"), "property" in x for objects with different properties, x instanceof Date for values made from a class, and x.kind === "..." for a discriminated union. After a branch that does return, what's left becomes the remaining type automatically. When every kind has been handled, what's left is never, and const check: never = x; becomes an alarm for a forgotten kind.
⚡ The type narrows inside the if
Write:
function getLength(input: string | string[]): number {
if (typeof input === "string") {
return input.length; // input: string
}
return input.length; // input: string[]
}
Meaning: Inside the if, TypeScript knows input is definitely a string. That branch already returns, so whatever reaches the line after it must be an array. You don't write a new type, TypeScript works it out from your check.
⚡ Arrays need Array.isArray
Guess first: what does typeof ["a", "b"] give?
"object", not "array", because in JavaScript an array is a kind of object. So typeof can't tell an array apart.
Meaning: For an array, check with Array.isArray(input). For objects, use "property" in x, and for values made from a class, x instanceof Date.
⚡ One telling property
Write:
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
function area(b: Circle | Square): number {
if (b.kind === "circle") {
return Math.PI * b.radius * b.radius; // b: Circle
}
return b.side * b.side; // b: Square
}
Meaning: Each member of the union has kind with a different literal value. Once b.kind is checked, only one shape fits, so b.radius can be used in that branch. This is called a discriminated union.