MST
星途 面试题库

面试题:TypeScript类型守卫与泛型的结合运用

实现一个TypeScript函数,它接受一个数组,数组元素类型不确定。要求利用类型守卫和泛型,将数组中的字符串元素提取出来组成新数组,同时保证新数组类型为string[],并对非字符串元素进行类型检查和合适的报错处理。
12.2万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function extractStrings<T>(arr: T[]): string[] {
    let result: string[] = [];
    for (let item of arr) {
        if (typeof item ==='string') {
            result.push(item);
        } else {
            console.error(`Element of type ${typeof item} is not a string.`);
        }
    }
    return result;
}