0
0
Typescriptprogramming~15 mins

Equality narrowing in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Equality narrowing
📖 Scenario: Imagine you are building a simple program that checks the status of a device. The device can be either "on" or "off". You want to write code that behaves differently depending on the device's status.
🎯 Goal: You will create a variable to hold the device status, then use equality narrowing to check if the device is "on" or "off" and print a message accordingly.
📋 What You'll Learn
Create a variable called deviceStatus with the exact value "on" or "off".
Create a variable called isOn that checks if deviceStatus is equal to "on".
Use an if statement with deviceStatus === "on" to print "The device is ON".
Use an else block to print "The device is OFF".
💡 Why This Matters
🌍 Real World
Checking device or system status is common in apps that control hardware or monitor conditions, like smart home devices or servers.
💼 Career
Understanding equality narrowing helps you write safer and clearer code that reacts correctly to different states or inputs.
Progress0 / 4 steps
1
Create the device status variable
Create a variable called deviceStatus and set it to the string "on".
Typescript
Need a hint?

Use let deviceStatus = "on"; to create the variable.

2
Create a boolean variable to check if device is on
Create a variable called isOn and set it to the result of checking if deviceStatus is equal to "on" using ===.
Typescript
Need a hint?

Use let isOn = deviceStatus === "on"; to create the boolean.

3
Use equality narrowing with an if statement
Write an if statement that checks if deviceStatus === "on". Inside the if, write a console.log to print "The device is ON". Use an else block to print "The device is OFF".
Typescript
Need a hint?

Use if (deviceStatus === "on") { console.log("The device is ON"); } else { console.log("The device is OFF"); }

4
Print the device status message
Run the program so it prints the correct message based on deviceStatus. The output should be exactly The device is ON.
Typescript
Need a hint?

Run the program and check the console output.