0
0
Typescriptprogramming~10 mins

Strict null checks and safety in Typescript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a variable that cannot be null or undefined.

Typescript
let name: string = [1];
Drag options to blanks, or click blank then click option'
A"Alice"
Bnull
Cundefined
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning null or undefined to a variable typed as string without union type.
2fill in blank
medium

Complete the code to allow the variable to hold either a string or null.

Typescript
let username: string[1] = null;
Drag options to blanks, or click blank then click option'
A& null
B| null
C? null
D?
Attempts:
3 left
💡 Hint
Common Mistakes
Using & instead of | for union types.
Using ? incorrectly for union types.
3fill in blank
hard

Fix the error by completing the code to safely access the length of a possibly null string.

Typescript
function getLength(str: string | null): number | undefined {
  return str[1].length;
}
Drag options to blanks, or click blank then click option'
A??
B!
C.
D?.
Attempts:
3 left
💡 Hint
Common Mistakes
Using dot operator directly causes error if str is null.
Using non-null assertion operator (!) does not check for null.
4fill in blank
hard

Fill both blanks to check if a variable is not null before accessing its property.

Typescript
if (user [1] null [2] user.name) {
  console.log(user.name);
}
Drag options to blanks, or click blank then click option'
A!==
B&&
C==
D||
Attempts:
3 left
💡 Hint
Common Mistakes
Using == instead of !== for null check.
Using || instead of && causing incorrect logic.
5fill in blank
hard

Fill all three blanks to create a function that returns the length of a string or zero if null or undefined.

Typescript
function safeLength(str: string[1]): number {
  return str?.length[2][3];
}
Drag options to blanks, or click blank then click option'
A| null | undefined
B??
C0
D||
Attempts:
3 left
💡 Hint
Common Mistakes
Using || instead of ?? which treats empty string as false.
Not allowing undefined in the type.