Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' without quotes causes a syntax error.
Comparing typeof to 'String' (capital S) is incorrect.
✗ Incorrect
Using typeof value === "string" narrows the type to string.
2fill in blank
mediumComplete 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'
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.
✗ Incorrect
Checking typeof input === "number" narrows input to number, allowing multiplication.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'bool' or 'Boolean' instead of 'boolean' causes the check to fail.
Misspelling the type string.
✗ Incorrect
The correct typeof string for boolean values is "boolean" all lowercase.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the order or using wrong type strings.
Using capitalized or incorrect type strings.
✗ Incorrect
Use typeof value === "string" to narrow to string and typeof value === "number" to narrow to number.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using capitalized or misspelled type strings.
Using 'bool' or 'Bool' instead of 'boolean'.
✗ Incorrect
Use "string", "number", and "boolean" to match the types returned by typeof.