MST

星途 面试题库

面试题:TypeScript中如何通过类型保护判断数组元素类型

假设有一个数组`let mixedArray: (string | number)[] = ['a', 1, 'b'];`,请编写一个函数`filterStrings`,使用类型保护,从这个数组中过滤出所有字符串类型的元素并返回。
29.8万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function filterStrings(mixedArray: (string | number)[]): string[] {
    return mixedArray.filter((element): element is string => typeof element ==='string');
}