0
0
Typescriptprogramming~10 mins

typeof type guards 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 using typeof.

Typescript
if (typeof value === [1]) {
  console.log("It's a string!");
}
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 'string' without quotes.
Comparing to 'String' with uppercase S.
Using typeof value === string (missing quotes).
2fill in blank
medium

Complete the code to check if the variable is a number using typeof.

Typescript
if (typeof num === [1]) {
  console.log("It's a number!");
}
Drag options to blanks, or click blank then click option'
A"undefined"
B"string"
C"boolean"
D"number"
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Number' with uppercase N.
Comparing to 'num' instead of 'number'.
Missing quotes around 'number'.
3fill in blank
hard

Fix the error in the typeof check to correctly identify a boolean.

Typescript
if (typeof flag === [1]) {
  console.log("It's a boolean!");
}
Drag options to blanks, or click blank then click option'
A"string"
B"bool"
C"boolean"
D"Boolean"
Attempts:
3 left
💡 Hint
Common Mistakes
Using uppercase "Boolean" instead of lowercase.
Using "bool" which is not a valid typeof result.
Missing quotes around the type string.
4fill in blank
hard

Fill both blanks to create a type guard that checks if input is a string or a number.

Typescript
if (typeof input === [1] || typeof input === [2]) {
  console.log("Input is string or number");
}
Drag options to blanks, or click blank then click option'
A"string"
B"boolean"
C"number"
D"object"
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect type strings like "bool" or "object".
Using && instead of || which requires both types at once.
Missing quotes around type strings.
5fill in blank
hard

Fill all three blanks to create a function that returns the type of the value as a string using typeof.

Typescript
function getType(value: unknown): string {
  return typeof [1] [2] [3];
}
Drag options to blanks, or click blank then click option'
Avalue
B+
C""
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' instead of '+' for concatenation.
Not using quotes around the empty string.
Using a variable name other than 'value'.