面试题答案
一键面试1. typeof 类型保护
typeof
操作符可以用于在运行时检查变量的类型。在TypeScript中,它可以作为类型保护来缩小变量的类型范围。
示例:
function printValue(value: string | number) {
if (typeof value === 'string') {
console.log(value.length); // 这里 value 被类型保护为 string 类型,可访问 length 属性
} else {
console.log(value.toFixed(2)); // 这里 value 被类型保护为 number 类型,可访问 toFixed 方法
}
}
2. instanceof 类型保护
instanceof
用于检查对象是否是特定类的实例。在TypeScript中,它同样可以作为类型保护来确定对象的类型。
示例:
class Animal {}
class Dog extends Animal {
bark() {
console.log('Woof!');
}
}
class Cat extends Animal {
meow() {
console.log('Meow!');
}
}
function handleAnimal(animal: Animal) {
if (animal instanceof Dog) {
animal.bark(); // 这里 animal 被类型保护为 Dog 类型,可访问 bark 方法
} else if (animal instanceof Cat) {
animal.meow(); // 这里 animal 被类型保护为 Cat 类型,可访问 meow 方法
}
}
在复杂业务逻辑中利用类型保护提高代码安全性和可维护性
假设我们有一个处理用户输入的函数,用户可能输入不同类型的数据,包括字符串、数字、布尔值等,并且根据不同类型执行不同的业务逻辑。
interface UserInput {
value: string | number | boolean;
type: 'string' | 'number' | 'boolean';
}
function processUserInput(input: UserInput) {
if (input.type === 'string') {
// 使用类型断言进一步加强类型安全性
const strValue = input.value as string;
console.log(strValue.toUpperCase());
} else if (input.type === 'number') {
const numValue = input.value as number;
console.log(numValue * 2);
} else if (input.type === 'boolean') {
const boolValue = input.value as boolean;
console.log(boolValue ? 'Yes' : 'No');
}
}
在这个复杂业务逻辑中,通过在函数内部使用类似 input.type
的自定义类型保护,明确地根据不同类型执行不同操作,提高了代码的安全性,避免了类型不匹配导致的运行时错误。同时,代码结构清晰,便于维护,后续如果需要添加新的类型处理逻辑,只需在 if - else if
块中添加新的分支即可。