Complete the code to check if 'obj' is an instance of class 'User'.
if (obj [1] User) { console.log('It is a User'); }
The instanceof operator checks if an object is an instance of a class or constructor function.
Complete the code to define an interface 'Person' with a 'name' property.
interface Person {
[1]: string;
}The interface 'Person' requires a 'name' property of type string.
Fix the error in the code that tries to use 'instanceof' with an interface.
function checkPerson(obj: any) {
if ('name' [1] obj) {
console.log('Is a Person');
}
}You cannot use instanceof with interfaces because interfaces do not exist at runtime. Instead, use the in operator to check for property presence.
Fill the blank to create a type guard function that checks if an object implements the 'Person' interface.
function isPerson(obj: any): obj is Person {
return [1] obj;
}The in operator checks if the property exists in the object or its prototype chain. Here, we check if 'name' is in obj.
Fill all three blanks to create a safe type guard that checks if 'obj' implements 'Person' by verifying the 'name' property is a string.
function isPerson(obj: any): obj is Person {
return (typeof obj [1] 'object') [2] obj !== null && [3] in obj && typeof obj.name === 'string';
}|| instead of AND &&.This function first checks that obj is an object and not null, then checks if it has a 'name' property, and finally verifies that 'name' is a string.