1. 实现自定义类型保护函数
// 定义一个类型保护函数,判断对象是否具有特定属性且属性类型正确
function hasProperty<T, K extends keyof T>(obj: T, prop: K): obj is T & { [P in K]: NonNullable<T[P]> } {
return obj && (prop in obj) && obj[prop]!== null && obj[prop]!== undefined;
}
2. 在复杂函数中应用类型保护函数
// 定义一个复杂函数,处理不同类型的输入
function complexFunction(input: any) {
if (hasProperty(input, 'name') && typeof input.name ==='string' && hasProperty(input, 'age') && typeof input.age === 'number') {
// 这里可以安全地使用 input.name 和 input.age
console.log(`Name: ${input.name}, Age: ${input.age}`);
} else if (hasProperty(input, 'title') && typeof input.title ==='string') {
// 这里可以安全地使用 input.title
console.log(`Title: ${input.title}`);
} else {
console.log('Unrecognized input');
}
}
3. 优化运行时检查与提升健壮性说明
- 优化运行时检查:在复杂函数中,通过类型保护函数
hasProperty
,可以在运行时快速确定对象是否具有预期的属性以及属性类型是否正确。这避免了在访问属性时可能出现的null
、undefined
或类型不匹配的错误,减少了不必要的运行时错误检查逻辑。例如,如果没有类型保护函数,每次访问input.name
时都需要手动检查input
是否为null
或undefined
以及name
属性是否存在,而使用类型保护函数可以将这些检查封装起来,使代码更加简洁高效。
- 提升代码健壮性:类型保护函数使得代码对于不同类型输入的处理更加健壮。它确保了在特定逻辑分支中使用对象属性时,这些属性一定是存在且类型正确的。如果输入数据不符合预期格式,函数可以优雅地处理(例如输出
Unrecognized input
),而不是抛出难以调试的运行时错误,提高了整个程序的稳定性和可靠性。