Complete the code to check if the variable is a string before using string methods.
function printLength(value: string | number) {
if (typeof value === [1]) {
console.log(value.length);
}
}We check if value is a string before accessing length because only strings have the length property.
Complete the code to narrow the type using an instanceof check.
class Dog { bark() { console.log('Woof!'); } } function makeSound(animal: Dog | string) { if (animal instanceof [1]) { animal.bark(); } }
Using instanceof Dog narrows the type to Dog, so we can safely call bark().
Fix the error by narrowing the type before calling the method.
function getFirstChar(input: string | number) {
if (typeof input === "string") {
return input.[1](0);
}
}The charAt method works only on strings. We need to narrow the type or convert the number to string first.
Fill both blanks to correctly narrow the type and access the property.
function printId(id: string | { id: number }) {
if (typeof id === [1]) {
console.log(id.toUpperCase());
} else if (typeof id === [2]) {
console.log(id.id);
}
}We check if id is a string to use string methods, else if it's an object to access the id property.
Fill all three blanks to narrow types and safely access properties.
function process(value: string | number | boolean) {
if (typeof value === [1]) {
console.log(value.toUpperCase());
} else if (typeof value === [2]) {
console.log(value.toFixed(2));
} else if (typeof value === [3]) {
console.log(value ? 'True' : 'False');
}
}We check for string to use toUpperCase(), number to use toFixed(), and boolean to handle true/false values.