0
0
Typescriptprogramming~30 mins

Null and undefined types in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Null and Undefined Types in TypeScript
📖 Scenario: Imagine you are building a simple user profile system. Sometimes, users may not provide their middle name or phone number. You need to handle these cases safely in your code.
🎯 Goal: You will create variables that can hold null or undefined values and learn how to check and use them properly in TypeScript.
📋 What You'll Learn
Create variables with explicit types that allow null and undefined
Assign null and undefined to these variables
Use conditional checks to handle null and undefined safely
Print the results to show how the program handles missing values
💡 Why This Matters
🌍 Real World
Handling missing or optional user information is common in real applications like forms and profiles.
💼 Career
Understanding null and undefined types helps prevent errors and bugs in TypeScript code, a valuable skill for frontend and backend developers.
Progress0 / 4 steps
1
Create variables with null and undefined types
Create a variable called middleName with type string | null and assign it the value null. Also, create a variable called phoneNumber with type string | undefined and assign it the value undefined.
Typescript
Need a hint?

Use the union type with | to allow null or undefined values.

2
Add a user name variable
Create a variable called userName with type string and assign it the value "Alice".
Typescript
Need a hint?

Just create a normal string variable for the user name.

3
Check for null and undefined values
Write an if statement that checks if middleName is not null and prints "Middle name: " plus the value. Otherwise, print "No middle name provided". Then write another if statement that checks if phoneNumber is not undefined and prints "Phone number: " plus the value. Otherwise, print "No phone number provided".
Typescript
Need a hint?

Use strict inequality !== to check for null and undefined.

4
Print the user name
Write a console.log statement to print "User name: " plus the value of userName.
Typescript
Need a hint?

Use console.log("User name: " + userName) to print the user name.