0
0
Typescriptprogramming~10 mins

Null and undefined types 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 can only be null.

Typescript
let value: [1] = null;
Drag options to blanks, or click blank then click option'
Anull
Bundefined
Cstring
Dnumber
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'undefined' instead of 'null' for a variable assigned null.
Using 'string' or 'number' which do not accept null values.
2fill in blank
medium

Complete the code to declare a variable that can be either a string or undefined.

Typescript
let name: [1];
Drag options to blanks, or click blank then click option'
Astring | null
Bundefined
Cstring | undefined
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string | null' when the variable should allow undefined.
Using only 'undefined' which excludes string values.
3fill in blank
hard

Fix the error in the function parameter type to accept null or string.

Typescript
function greet(message: [1]) {
  console.log(message);
}
Drag options to blanks, or click blank then click option'
Astring
Bstring | null
Cnull
Dundefined
Attempts:
3 left
💡 Hint
Common Mistakes
Using only 'string' which rejects null values.
Using 'null' alone which rejects string values.
4fill in blank
hard

Fill both blanks to create a variable that can be a number, null, or undefined.

Typescript
let count: [1] [2] null | undefined;
Drag options to blanks, or click blank then click option'
Anumber
B|
C&
Dstring
Attempts:
3 left
💡 Hint
Common Mistakes
Using '&' which means intersection, not union.
Using 'string' which is not part of the allowed types.
5fill in blank
hard

Fill all three blanks to define a function that returns a string or undefined and accepts a nullable string parameter.

Typescript
function process(input: [1]): [2] [3] undefined {
  if (input === null) return undefined;
  return input.toUpperCase();
}
Drag options to blanks, or click blank then click option'
Astring | null
Bstring
C|
Dundefined
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' alone for parameter or return type, which excludes null or undefined.
Using '&' instead of '|' for union types.