0
0
Typescriptprogramming~10 mins

Equality narrowing 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 check if the variable is a string.

Typescript
function checkType(x: string | number) {
  if (typeof x === [1]) {
    return x.toUpperCase();
  }
  return x;
}
Drag options to blanks, or click blank then click option'
A"object"
B"number"
C"string"
D"boolean"
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' without quotes
Checking for 'text' instead of 'string'
Using typeof x === string (missing quotes)
2fill in blank
medium

Complete the code to narrow the type using equality check.

Typescript
function process(value: string | null) {
  if (value [1] null) {
    return value.toLowerCase();
  }
  return "No value";
}
Drag options to blanks, or click blank then click option'
A!=
B===
C==
D!==
Attempts:
3 left
💡 Hint
Common Mistakes
Using == instead of === or !==
Calling string methods on null values
Confusing === and !== operators
3fill in blank
hard

Fix the error in the equality narrowing condition.

Typescript
function example(input: string | number) {
  if (typeof input [1] "string") {
    return input.toLowerCase();
  }
  return input;
}
Drag options to blanks, or click blank then click option'
A!=
B===
C!==
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using == instead of ===
Comparing value directly to "string" instead of using typeof
Using !== instead of ===
4fill in blank
hard

Fill both blanks to correctly narrow the type and use the value.

Typescript
function handle(input: string | number) {
  if (typeof input [1] [2]) {
    return input.toUpperCase();
  }
  return input.toFixed(2);
}
Drag options to blanks, or click blank then click option'
A===
B"string"
C"number"
D!==
Attempts:
3 left
💡 Hint
Common Mistakes
Using !== instead of ===
Using 'number' instead of 'string' in the check
Missing quotes around the type string
5fill in blank
hard

Fill all three blanks to correctly narrow types and handle both cases.

Typescript
function format(value: string | number | null) {
  if (value [1] null) {
    if (typeof value [2] [3]) {
      return value.toUpperCase();
    }
    return value.toFixed(1);
  }
  return "No value";
}
Drag options to blanks, or click blank then click option'
A!==
B===
C"string"
D"number"
Attempts:
3 left
💡 Hint
Common Mistakes
Using == instead of !== for null check
Mixing up === and !== in type checks
Calling string methods on numbers or null