0
0
Typescriptprogramming~10 mins

Why type narrowing is needed in Typescript - Test Your Understanding

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 before using string methods.

Typescript
function printLength(value: string | number) {
  if (typeof value === [1]) {
    console.log(value.length);
  }
}
Drag options to blanks, or click blank then click option'
A"number"
B"string"
C"boolean"
D"object"
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for 'number' instead of 'string' causes errors when accessing length.
Not checking type at all leads to runtime errors.
2fill in blank
medium

Complete the code to narrow the type using an instanceof check.

Typescript
class Dog {
  bark() { console.log('Woof!'); }
}

function makeSound(animal: Dog | string) {
  if (animal instanceof [1]) {
    animal.bark();
  }
}
Drag options to blanks, or click blank then click option'
ADog
BArray
CObject
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'String' instead of 'Dog' causes the check to fail.
Using instanceof on primitive types like string is invalid.
3fill in blank
hard

Fix the error by narrowing the type before calling the method.

Typescript
function getFirstChar(input: string | number) {
  if (typeof input === "string") {
    return input.[1](0);
  }
}
Drag options to blanks, or click blank then click option'
AtoString
Blength
Cslice
DcharAt
Attempts:
3 left
💡 Hint
Common Mistakes
Calling charAt on a number causes runtime errors.
Using length or toString directly without narrowing causes confusion.
4fill in blank
hard

Fill both blanks to correctly narrow the type and access the property.

Typescript
function printId(id: string | { id: number }) {
  if (typeof id === [1]) {
    console.log(id.toUpperCase());
  } else if (typeof id === [2]) {
    console.log(id.id);
  }
}
Drag options to blanks, or click blank then click option'
A"string"
B"number"
C"object"
D"boolean"
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for 'number' instead of 'object' causes errors.
Not handling both types leads to runtime errors.
5fill in blank
hard

Fill all three blanks to narrow types and safely access properties.

Typescript
function process(value: string | number | boolean) {
  if (typeof value === [1]) {
    console.log(value.toUpperCase());
  } else if (typeof value === [2]) {
    console.log(value.toFixed(2));
  } else if (typeof value === [3]) {
    console.log(value ? 'True' : 'False');
  }
}
Drag options to blanks, or click blank then click option'
A"string"
B"number"
C"boolean"
D"object"
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up type checks causes runtime errors.
Not checking for all types leads to missing cases.