Variables Without a Value

A variable created without a value, such as let reward: number;, has no value at first: in JavaScript, it holds undefined. The value is stored in it later, often in the branches of an if. TypeScript follows every path through the program and checks that wherever you use the variable, it surely has a value:

let monster = "goblin";
let reward: number;

if (monster === "wolf") {
    reward = 50;
} else if (monster === "goblin") {
    reward = 20;
}

console.log("Reward:", reward);
main.ts(10,24): error TS2454: Variable 'reward' is used before being assigned.

The message says that the variable is used before a value is assigned to it. But the monster is a goblin, so reward gets 20, doesn't it? This time, yes. TypeScript doesn't look at what monster holds right now, though. It checks every path the program could take. If the monster were a dragon, neither branch would run, and the program would print Reward: undefined. A calculation such as gold + reward would then give NaN.

To fix it, make sure that every path stores a value, most often with an else branch, which runs in all the other cases:

if (monster === "wolf") {
    reward = 50;
} else if (monster === "goblin") {
    reward = 20;
} else {
    reward = 0;
}

Another way is a starting value: let reward = 0;. The variable then has a value from the start, the branches only change it, and you don't even need the type, because TypeScript infers it from the 0. Choose what fits: a starting value when there is a sensible one, and a variable without a value when the value really comes only from the branches. TypeScript then checks that you haven't forgotten any of them.

Typical mistakes:

  • An if or else if without a final else.
  • A branch that does something else and forgets to store the value.
  • Using a variable that never gets a value at all: let reward: number; followed by console.log(reward); gives the same TS2454.

Instructions

Run the program: TypeScript reports TS2454 twice. The else branch, for the large room, forgot to set the price. The large room costs 25 gold. Fix the branch so that the program prints:

The best room in the house!
Kira pays 25 gold. Gold left: 95

Bruno also serves dinner, and it depends on the room too. Below price, create a variable meal of the type string without a value. Then store a value in it in each of the three branches: "bread" for the small room, "soup" for the medium one and "roast chicken" for the large one.

At the end of the program, print the dinner, so that the program also prints:

Dinner: roast chicken

If TypeScript reports TS2454 for meal, check that every branch stores a value in it.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

3/9