Look at the code below. What will it print when run?
function printLength(x: string | number) { if (typeof x === 'string') { console.log(x.length); } else { console.log(x.toFixed(2)); } } printLength('hello'); printLength(3.14159);
Think about how TypeScript knows what methods are safe to call on x.
Type narrowing lets TypeScript know if x is a string or number inside the if and else blocks. So it safely calls length for strings and toFixed for numbers.
Choose the best reason why type narrowing is important in TypeScript.
Think about how TypeScript prevents errors when a variable can be more than one type.
Type narrowing helps TypeScript understand the exact type of a variable at a certain point, so it can allow safe access to properties or methods that only exist on that type.
Look at this code. What error will TypeScript show?
function doubleValue(x: string | number) { return x * 2; }
Think about what happens when you try to multiply a string by a number in TypeScript.
TypeScript does not allow using '*' on a union type without knowing the exact type. It raises an error because x could be a string, and multiplying a string by a number is invalid.
Choose the correct way to narrow the type of value to string before calling toUpperCase().
function shout(value: string | number) { // Narrow value to string here console.log(value.toUpperCase()); }
Remember how to check the type of a variable in JavaScript/TypeScript.
The typeof operator returns the type as a string. Checking typeof value === 'string' narrows the type correctly. instanceof String checks for String objects, not string primitives.
Consider this code with a custom type guard function. What will it print?
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
function move(pet: Fish | Bird) {
if (isFish(pet)) {
return 'Fish swims';
} else {
return 'Bird flies';
}
}
console.log(move({ swim: () => {} }));
console.log(move({ fly: () => {} }));Look at how the custom type guard works and what it checks.
The isFish function checks if the object has a swim method. The first object has swim, so it returns "Fish swims". The second has fly, so it returns "Bird flies".