MST
星途 面试题库

面试题:TypeScript复杂类型守卫与类型缩小应用

定义一个包含多种类型的联合类型数组,比如 [string, number, boolean, null] 组成的数组。编写一个函数,使用类型守卫和类型缩小,将数组中的string类型元素提取出来,并组成一个新的字符串,按元素在原数组中的顺序拼接。
17.1万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function extractStrings(arr: (string | number | boolean | null)[]): string {
    let result = '';
    for (let item of arr) {
        if (typeof item ==='string') {
            result += item;
        }
    }
    return result;
}

示例调用:

const mixedArray: (string | number | boolean | null)[] = ['hello', 123, true, null, 'world'];
const extractedString = extractStrings(mixedArray);
console.log(extractedString);