0
0
Typescriptprogramming~15 mins

Nullish coalescing with types in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Nullish coalescing with types
📖 Scenario: You are building a simple user profile display. Sometimes, the user data might be missing or undefined. You want to safely provide default values using nullish coalescing.
🎯 Goal: Create a TypeScript program that uses nullish coalescing to assign default values to possibly undefined user properties.
📋 What You'll Learn
Create an object with user data that may have undefined properties
Create a default value variable for the user's city
Use nullish coalescing to assign a city value safely
Print the final city value
💡 Why This Matters
🌍 Real World
Nullish coalescing helps handle missing or undefined data safely, common in user input or API responses.
💼 Career
Understanding nullish coalescing is important for writing robust TypeScript code that avoids bugs from undefined or null values.
Progress0 / 4 steps
1
Create user data with possible undefined properties
Create a constant object called user with the properties name set to "Alice" and city set to undefined.
Typescript
Need a hint?

Use const user = { name: "Alice", city: undefined };

2
Create a default city value
Create a constant called defaultCity and set it to the string "New York".
Typescript
Need a hint?

Use const defaultCity = "New York";

3
Use nullish coalescing to assign city
Create a constant called city and assign it the value of user.city ?? defaultCity using nullish coalescing.
Typescript
Need a hint?

Use const city = user.city ?? defaultCity; to assign city safely.

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

Use console.log(city); to show the city.