0
0
Typescriptprogramming~10 mins

Type predicates in practice 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 define a type predicate function that checks if a value is a string.

Typescript
function isString(value: unknown): value is string {
  return typeof value === [1];
}
Drag options to blanks, or click blank then click option'
A"object"
B"number"
C"boolean"
D"string"
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' without quotes causes a syntax error.
Checking for 'number' instead of 'string' returns wrong results.
2fill in blank
medium

Complete the code to use the type predicate function in a conditional statement.

Typescript
function printLength(value: unknown) {
  if ([1](value)) {
    console.log(value.length);
  } else {
    console.log("Not a string");
  }
}
Drag options to blanks, or click blank then click option'
AisNumber
BisString
CisBoolean
DisObject
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong predicate function like isNumber causes errors.
Not calling the function with parentheses causes syntax errors.
3fill in blank
hard

Fix the error in the type predicate function that checks if a value is an array of numbers.

Typescript
function isNumberArray(value: unknown): value is number[] {
  return Array.isArray(value) && value.every(item => typeof item === [1]);
}
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 "string" instead of "number" causes wrong results.
Not using quotes around the type string causes syntax errors.
4fill in blank
hard

Fill both blanks to create a type predicate that checks if a value is an object with a 'name' property of type string.

Typescript
function hasNameProperty(value: unknown): value is [1] {
  return typeof value === [2] && value !== null && 'name' in value && typeof (value as any).name === 'string';
}
Drag options to blanks, or click blank then click option'
Aobject
B"string"
C"object"
Dstring
Attempts:
3 left
💡 Hint
Common Mistakes
Using quotes around the type in the first blank causes errors.
Using 'object' without quotes in the second blank causes wrong runtime checks.
5fill in blank
hard

Fill all three blanks to create a type predicate that checks if a value is a function with a 'length' property greater than 1.

Typescript
function isFunctionWithLength(value: unknown): value is [1] {
  return typeof value === [2] && value !== null && (value as Function).length [3] 1;
}
Drag options to blanks, or click blank then click option'
AFunction
B"function"
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'function' without quotes in the second blank causes errors.
Using '<' instead of '>' in the third blank causes wrong logic.