0
0
Typescriptprogramming~15 mins

NonNullable type in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the NonNullable Type in TypeScript
📖 Scenario: Imagine you are building a simple app that stores user preferences. Sometimes, the preferences might be missing or set to null or undefined. You want to make sure you only work with preferences that have real values.
🎯 Goal: Learn how to use the NonNullable type in TypeScript to remove null and undefined from a type, so you can safely use values without extra checks.
📋 What You'll Learn
Create a variable with a type that includes string, null, and undefined
Create a new type using NonNullable to exclude null and undefined
Create a variable using the new NonNullable type
Print the original and filtered variables to see the difference
💡 Why This Matters
🌍 Real World
In real apps, user data or settings might be missing or not set. Using <code>NonNullable</code> helps avoid errors by ensuring you only work with real values.
💼 Career
Understanding TypeScript utility types like <code>NonNullable</code> is important for writing safe and clean code in professional web development.
Progress0 / 4 steps
1
Create a variable with a union type including null and undefined
Create a variable called userPreference with the type string | null | undefined and assign it the value null.
Typescript
Need a hint?

Use let userPreference: string | null | undefined = null; to create the variable.

2
Create a NonNullable type to exclude null and undefined
Create a new type called SafePreference using NonNullable applied to typeof userPreference.
Typescript
Need a hint?

Use type SafePreference = NonNullable; to create the new type.

3
Create a variable using the NonNullable type
Create a variable called confirmedPreference of type SafePreference and assign it the string value 'dark mode'.
Typescript
Need a hint?

Assign a string value to confirmedPreference with the type SafePreference.

4
Print the original and NonNullable variables
Write two console.log statements to print userPreference and confirmedPreference.
Typescript
Need a hint?

Use console.log(userPreference); and console.log(confirmedPreference); to show the values.