MST
星途 面试题库

面试题:TypeScript 函数中复杂参数与返回值类型处理

编写一个 TypeScript 函数,它接受一个数组作为参数,数组中的元素可以是数字或者字符串。函数需要遍历这个数组,将所有数字元素相加,所有字符串元素连接起来,最后以一个对象的形式返回,对象包含两个属性:sum(数字之和)和concatStr(连接后的字符串)。请正确使用类型别名或接口来定义函数的参数和返回值类型。
26.5万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 使用类型别名定义数组元素类型
type ArrayElement = string | number; 
// 使用接口定义返回值类型
interface Result {
    sum: number;
    concatStr: string;
}

function processArray(arr: ArrayElement[]): Result {
    let sum = 0;
    let concatStr = '';
    for (let element of arr) {
        if (typeof element === 'number') {
            sum += element;
        } else if (typeof element ==='string') {
            concatStr += element;
        }
    }
    return { sum, concatStr };
}