Learn/TypeScript/4. Making decisions
Lesson 4 of 15
Sign in

TypeScript, lesson 4

Making decisions

Programs make choices: charge a child's fare, warn when the battery is low, pick a winner. TypeScript uses the same decision-making tools as JavaScript, and adds something useful on top: inside each branch it knows more about your variables' types.

if, else if, else

The conditions are checked from the top. The first true one wins and the rest are skipped.

Comparing

OperatorMeaning
===, !==equal, not equal (no type conversion)
<, , ,

2 exercises to try what you just read.

Exercise 1

Cinema prices

Press Ctrl Enter or Check to test your code.

Exercise 2

Rock, paper, scissors

Press Ctrl Enter or Check to test your code.

<=
>
>=
ordering

Always use === and !==. The loose == converts types first ("1" == 1 is true), which hides bugs. TypeScript even reports an error when you compare values that can never be equal, such as a number with a string, because that comparison is always false.

Combine conditions with && (and), || (or) and ! (not). && and || stop early once the answer is known.

Truthiness

if accepts any value. false, 0, NaN, "", null and undefined count as false (falsy); everything else counts as true. That makes if (name) a quick "not empty" test, but be careful when 0 is a valid number.

The conditional operator

switch

switch compares one value against several exact cases using ===:

Without a return or break, execution falls through into the next case. Here every case returns, so no break is needed. Notice that TypeScript is happy without a default: it knows move can only be one of the three values, and all three are handled.

Narrowing

When a variable can be one of several types, a check inside an if narrows it. The type checker follows your logic:

Calling toFixed on a number | string without the check would be an error, because strings have no toFixed. Narrowing works with typeof, ===, truthiness checks and more; it is one of the features that make TypeScript feel like a helpful colleague.

Input is always text, so in exercises you check its content and convert it, and the checker makes sure each branch only does what is valid for its type.

Further reading

  • TypeScript Handbook: Narrowing
  • MDN: Control flow and error handling
  • MDN: Equality comparisons and sameness

A cinema prices tickets by age:

  • under 4: free (0)
  • 4 to 12: 6
  • 13 to 64: 11
  • 65 and over: 7

On Tuesdays every non-free ticket costs 3 less. The input is one line with an age and a day name in lower case, like 30 tuesday. Print Price: N.

Sample input:

Sample output:

The input is one line with two moves: player one's and player two's, each rock, paper or scissors. Rock beats scissors, scissors beats paper, paper beats rock. Print Player 1 wins, Player 2 wins or Draw.

Sample input:

Sample output:

The starter defines a Move type. Write a function beats(move: Move): Move with a switch that returns the move each move defeats, then use it to decide the winner.

const battery = 14;

if (battery <= 5) {
  console.log("Critical");
} else if (battery <= 20) {
  console.log("Low");
} else {
  console.log("OK");
}
const tickets = 1;
const label = tickets === 1 ? "ticket" : "tickets";
type Move = "rock" | "paper" | "scissors";

function beats(move: Move): Move {
  switch (move) {
    case "rock":
      return "scissors";
    case "paper":
      return "rock";
    case "scissors":
      return "paper";
  }
}
function describe(value: number | string): string {
  if (typeof value === "number") {
    return `the number ${value.toFixed(1)}`;   // here value is a number
  }
  return `the text "${value.toUpperCase()}"`;  // here value must be a string
}
30 tuesday
Price: 8
rock scissors
Player 1 wins