0
0
Typescriptprogramming~10 mins

Type narrowing with typeof 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
if (typeof value === [1]) {
  console.log("It's a string!");
}
Drag options to blanks, or click blank then click option'
A"object"
B"string"
C"boolean"
D"number"
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' without quotes causes a syntax error.
Comparing typeof to 'String' (capital S) is incorrect.
2fill in blank
medium

Complete the code to narrow the type to number.

Typescript
function double(input: string | number) {
  if (typeof input === [1]) {
    return input * 2;
  }
  return input + input;
}
Drag options to blanks, or click blank then click option'
A"string"
B"object"
C"boolean"
D"number"
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Number' instead of 'number' causes the condition to fail.
Checking for 'string' when you want to double a number.
3fill in blank
hard

Fix the error in the type narrowing condition.

Typescript
function isBoolean(value: unknown): boolean {
  if (typeof value === [1]) {
    return true;
  }
  return false;
}
Drag options to blanks, or click blank then click option'
A"boolean"
B"Boolean"
C"bool"
D"boolian"
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'bool' or 'Boolean' instead of 'boolean' causes the check to fail.
Misspelling the type string.
4fill in blank
hard

Fill both blanks to create a type guard for strings and numbers.

Typescript
function process(value: string | number) {
  if (typeof value === [1]) {
    return value.toUpperCase();
  } else if (typeof value === [2]) {
    return value + 10;
  }
}
Drag options to blanks, or click blank then click option'
A"string"
B"boolean"
C"number"
D"object"
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the order or using wrong type strings.
Using capitalized or incorrect type strings.
5fill in blank
hard

Fill all three blanks to create a type guard that handles string, number, and boolean types.

Typescript
function describe(value: string | number | boolean) {
  switch (typeof value) {
    case [1]:
      return `String: ${value.toLowerCase()}`;
    case [2]:
      return `Number: ${value + 1}`;
    case [3]:
      return `Boolean: ${value ? 'yes' : 'no'}`;
  }
}
Drag options to blanks, or click blank then click option'
A"string"
B"number"
C"boolean"
D"object"
Attempts:
3 left
💡 Hint
Common Mistakes
Using capitalized or misspelled type strings.
Using 'bool' or 'Bool' instead of 'boolean'.