风险分析
- 类型不匹配风险:如果断言的类型与实际对象结构不匹配,可能导致运行时错误。例如将一个不包含特定属性的对象断言为包含该属性的类型,访问该属性时会出现
undefined
错误。
- 丢失原有类型信息风险:过度断言可能会丢失对象原本具有的一些类型信息,使得后续代码无法正确利用这些信息进行类型检查和推导。
规避策略及代码示例
- 使用类型守卫
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
function handleAnimal(animal: Animal) {
if ('bark' in animal) {
(animal as Dog).bark();
}
}
- 使用
is
类型谓词
interface Fish {
swim(): void;
}
interface Bird {
fly(): void;
}
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim!== undefined;
}
function handlePet(pet: Fish | Bird) {
if (isFish(pet)) {
pet.swim();
} else {
(pet as Bird).fly();
}
}
- 使用
infer
关键字进行类型推断
type Flatten<T> = T extends Array<infer U> ? U : T;
interface ComplexObject {
data: Array<{ value: string | number }>;
}
function processComplexObject(obj: ComplexObject) {
const flatValue: Flatten<ComplexObject['data'][number]['value']> = obj.data[0].value;
// 这里 flatValue 会根据实际值推断为 string | number
}