MST

星途 面试题库

面试题:TypeScript类型断言在复杂类型转换中的应用

假设你有一个包含多种类型元素的数组,如string、number和自定义接口类型的混合数组。要求通过类型断言,将其中符合特定条件的元素提取出来,并转换为特定类型进行后续操作,编写相关代码实现该功能,并解释类型断言在其中起到的作用。
41.6万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 自定义接口
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);

类型断言的作用

  1. 明确类型转换意图:在map方法中,使用类型断言<T>element,告诉TypeScript编译器开发者明确知道element的类型符合<T>指定的类型,从而将element转换为指定类型T,避免类型错误。
  2. 绕过类型检查:TypeScript默认情况下不会自动将any类型(这里filter之后的元素类型为any)转换为特定类型。通过类型断言,开发者可以绕过编译器的部分类型检查机制,强制将元素转换为所需类型,以便进行后续特定类型的操作。例如在上述代码中,将经过filter筛选后的元素明确转换为MyInterface类型数组,方便后续对MyInterface类型元素的属性进行访问等操作。