Bitpath

Lesson 1 · Unit 06

Unions and narrowing

A value that is one of several types, and how to find out which

13 exercisesabout 3 min

What you practise

  • string | number, literal types, null and undefined under strict, narrowing with typeof and ===, ?. and ??, a kind field that tells shapes apart

Try a question from this lesson

Pick one

The type string | number reads "a string or a number". Which line does the compiler reject?

TypeScript
let id: string | number = 7;
id = "A7";
id = true;

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Narrowing

A union type lists alternatives. Before you use the value as one of them, prove which one it is.

typeof gives the kind of a value as text: "number", "string", "boolean". Inside the if, the compiler has narrowed id to number. After it, only string is left.

TypeScript
type Id = string | number;

function show(id: Id): string {
  if (typeof id === "number") {
    return `#${id + 1}`; // number here
  }
  return id.toUpperCase(); // string here
}
console.log(show(7), show("a7")); // #8 A7

Concept

Literal types

A union can list exact values instead of whole types. "left" | "right" allows those two strings and nothing else.

A typo is no longer a string that happens to be wrong. It is a value outside the type, and the compiler catches it before the program runs.

TypeScript
type Dir = "left" | "right";

let d: Dir = "left";
d = "right";

// d = "rihgt";
// rejected: "rihgt" is not a Dir

Concept

null and undefined

undefined means "nothing was ever put here". null means "empty on purpose". Under strict neither may hide inside a string: the type has to say string | null.

Two shortcuts help. a?.b reads b only if a is there, and gives undefined if not. a ?? b means: use a, unless it is null or undefined, then use b.

TypeScript
const names = ["ada", "bo"];
const hit = names.find((n) => n === "cy");
// hit is string | undefined

console.log(hit?.length);     // undefined
console.log(hit ?? "nobody"); // nobody

9 more exercises in the app

  • 3× multiple choice
  • 1× fill the blanks
  • 3× type the answer
  • 1× true or false
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy