Complete the code to declare a custom type guard function that checks if a value is a string.
function isString(value: unknown): value is string {
return typeof value === [1];
}The typeof operator returns a string describing the type. To check if a value is a string, compare it to "string".
Complete the code to create a custom type guard that checks if an object has a 'name' property of type string.
function hasName(obj: unknown): obj is { name: string } {
return typeof obj === [1] &&
obj !== null &&
'name' in obj &&
typeof (obj as any).name === 'string';
}To check if obj is an object, use typeof obj === "object". This ensures obj is not a primitive type.
Fix the error in the custom type guard function that checks if a value is an array of numbers.
function isNumberArray(value: unknown): value is number[] {
return Array.isArray(value) && value.every(item => typeof item === [1]);
}The typeof operator should check if each item is a "number" to confirm the array contains only numbers.
Fill both blanks to create a custom type guard that checks if an object is a Person with a 'name' string and 'age' number.
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];
}First, check that obj is an object. Then check that obj.name is a string and obj.age is a number.
Fill all three blanks to create a custom type guard that checks if a value is a tuple of [string, number, boolean].
function isTuple(value: unknown): value is [string, number, boolean] {
return Array.isArray(value) &&
value.length === [1] &&
typeof value[0] === [2] &&
typeof value[1] === [3];
}The tuple has length 3. The first element is a string, the second is a number, and the third is a boolean (not checked here but could be added).