0
0
Typescriptprogramming~10 mins

Custom type guard functions 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 declare a custom type guard 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"string"
B"number"
C"boolean"
D"object"
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong string in the typeof comparison.
Forgetting to put quotes around the type name.
2fill in blank
medium

Complete the code to create a custom type guard that checks if an object has a 'name' property of type string.

Typescript
function hasName(obj: unknown): obj is { name: string } {
  return typeof obj === [1] &&
         obj !== null &&
         'name' in obj &&
         typeof (obj as any).name === 'string';
}
Drag options to blanks, or click blank then click option'
A"object"
B"number"
C"string"
D"boolean"
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for 'string' instead of 'object' in typeof.
Not checking for null before accessing properties.
3fill in blank
hard

Fix the error in the custom type guard 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"string"
B"number"
C"object"
D"boolean"
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for 'string' instead of 'number'.
Not using Array.isArray to check if value is an array.
4fill in blank
hard

Fill both blanks to create a custom type guard that checks if an object is a Person with a 'name' string and 'age' number.

Typescript
function isPerson(obj: unknown): obj is { name: string; age: number } {
  return typeof obj === [1] &&
         obj !== null &&
         typeof (obj as any).name === 'string' &&
         typeof (obj as any).age === [2];
}
Drag options to blanks, or click blank then click option'
A"object"
B"string"
C"number"
D"boolean"
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong type strings in typeof checks.
Not checking for null before property access.
5fill in blank
hard

Fill all three blanks to create a custom type guard that checks if a value is a tuple of [string, number, boolean].

Typescript
function isTuple(value: unknown): value is [string, number, boolean] {
  return Array.isArray(value) &&
         value.length === [1] &&
         typeof value[0] === [2] &&
         typeof value[1] === [3];
}
Drag options to blanks, or click blank then click option'
A3
B"string"
C"number"
D"boolean"
Attempts:
3 left
💡 Hint
Common Mistakes
Not checking the length of the array.
Using wrong type strings in typeof checks.