- 编写类型保护函数:
function isObjectWithName(value: any): value is { name: string } {
return typeof value === 'object' && 'name' in value && typeof value.name ==='string';
}
function filterObjectsWithName(arr: (string | number | { name: string })[]): { name: string }[] {
return arr.filter(isObjectWithName);
}
- 类型推断机制说明:
- 在
isObjectWithName
函数中,通过 typeof value === 'object'
首先判断 value
是一个对象。然后,使用 'name' in value
确保对象有 name
属性,最后通过 typeof value.name ==='string'
确定 name
属性的值是字符串类型。通过这些条件组合,isObjectWithName
函数可以准确判断传入的值是否是具有 name
属性且值为字符串的对象。
- 在
filterObjectsWithName
函数中,调用 arr.filter(isObjectWithName)
时,TypeScript 会利用 isObjectWithName
这个类型保护函数的返回值类型(value is { name: string }
)来进行类型推断。filter
方法会对数组中的每个元素调用 isObjectWithName
,如果返回 true
,则该元素会被保留在结果数组中,并且在结果数组中,TypeScript 能够推断出这些元素的类型是 { name: string }
。所以最终 filterObjectsWithName
函数返回的数组类型就是 { name: string }[]
。