0
0
Typescriptprogramming~15 mins

Strict null checks and safety in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Strict null checks and safety
📖 Scenario: You are building a simple user profile system where some user information might be missing. You want to make sure your TypeScript code safely handles cases where values can be null or undefined.
🎯 Goal: Create a TypeScript program that uses strict null checks to safely access user data and avoid runtime errors.
📋 What You'll Learn
Create a user object with some properties possibly null or undefined.
Add a configuration variable to control if the user is active.
Use strict null checks to safely access user properties.
Print the user's name or a default message if the name is missing.
💡 Why This Matters
🌍 Real World
Handling user data safely is important in web apps where some information might be missing or optional.
💼 Career
Strict null checks help prevent runtime errors and improve code quality in TypeScript projects.
Progress0 / 4 steps
1
Create a user object with nullable properties
Create a constant called user with type { name: string | null; age: number | undefined; } and assign it the value { name: null, age: undefined }.
Typescript
Need a hint?

Use | null and | undefined to allow properties to be missing.

2
Add an active status configuration variable
Create a boolean variable called isActive and set it to true.
Typescript
Need a hint?

Use let isActive: boolean = true; to declare the variable.

3
Use strict null checks to safely access user name
Create a constant called displayName that uses a conditional expression to assign user.name if it is not null, otherwise assign the string 'Guest'.
Typescript
Need a hint?

Use user.name !== null ? user.name : 'Guest' to safely assign the name.

4
Print the display name
Write a console.log statement to print the value of displayName.
Typescript
Need a hint?

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