// 自定义接口
interface MyInterface {
id: number;
name: string;
}
function extractAndConvert<T>(arr: (string | number | MyInterface)[], condition: (element: any) => boolean): T[] {
return arr.filter(condition).map((element) => <T>element);
}
// 示例使用
const mixedArray: (string | number | MyInterface)[] = ["hello", 123, { id: 1, name: "test" }, 456, "world"];
// 提取自定义接口类型的元素
const myInterfaceElements = extractAndConvert<MyInterface>(mixedArray, (element): element is MyInterface => {
return typeof element === 'object' && 'id' in element && 'name' in element;
});
console.log(myInterfaceElements);
类型断言的作用
- 明确类型转换意图:在
map
方法中,使用类型断言<T>element
,告诉TypeScript编译器开发者明确知道element
的类型符合<T>
指定的类型,从而将element
转换为指定类型T
,避免类型错误。
- 绕过类型检查:TypeScript默认情况下不会自动将
any
类型(这里filter
之后的元素类型为any
)转换为特定类型。通过类型断言,开发者可以绕过编译器的部分类型检查机制,强制将元素转换为所需类型,以便进行后续特定类型的操作。例如在上述代码中,将经过filter
筛选后的元素明确转换为MyInterface
类型数组,方便后续对MyInterface
类型元素的属性进行访问等操作。