MST

星途 面试题库

面试题:TypeScript元组的解构与扩展

编写一个TypeScript函数,它接受一个包含至少三个元素(数字、字符串、布尔值)的元组作为参数。在函数内部,使用解构来获取元组的各个元素,并将它们拼接成一个新的字符串返回。此外,展示如何在定义函数参数时,使用元组类型的扩展,允许额外的元素。
37.8万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function combineTupleElements([num, str, bool, ...rest]: [number, string, boolean, ...any[]]): string {
    let result = num.toString() + str + bool.toString();
    rest.forEach(element => {
        result += element.toString();
    });
    return result;
}

示例调用:

let tuple1: [number, string, boolean, string] = [1, 'hello', true, 'world'];
let combined = combineTupleElements(tuple1);
console.log(combined);