0
0
Typescriptprogramming~15 mins

Truthiness narrowing in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Truthiness Narrowing in TypeScript
📖 Scenario: You are building a simple program that checks user input values and decides if they are valid or not based on whether they are "truthy" or "falsy" in TypeScript.
🎯 Goal: Learn how to use truthiness narrowing to check if a variable has a meaningful value before using it.
📋 What You'll Learn
Create a variable with a value that can be truthy or falsy
Create a boolean variable to hold the check result
Use an if statement to narrow the type by checking truthiness
Print the result to the console
💡 Why This Matters
🌍 Real World
Checking if user inputs or data values exist before using them is common in web forms and applications.
💼 Career
Understanding truthiness narrowing helps avoid errors and write safer TypeScript code in real projects.
Progress0 / 4 steps
1
Create a variable with a value that can be truthy or falsy
Create a variable called userInput and assign it the value "Hello".
Typescript
Need a hint?

Use let userInput: string | null = "Hello"; to allow userInput to be a string or null.

2
Create a boolean variable to hold the check result
Create a boolean variable called isValid and set it to false.
Typescript
Need a hint?

Use let isValid: boolean = false; to create the boolean variable.

3
Use an if statement to narrow the type by checking truthiness
Use an if statement to check if userInput is truthy. Inside the if, set isValid to true.
Typescript
Need a hint?

Use if (userInput) { isValid = true; } to check truthiness and update isValid.

4
Print the result to the console
Write a console.log statement to print the value of isValid.
Typescript
Need a hint?

Use console.log(isValid); to show the result.