MST

星途 面试题库

面试题:TypeScript中可选参数与剩余参数结合使用基础

请编写一个TypeScript函数,它接受一个必选字符串参数,一个可选的数字参数,以及任意数量的布尔值作为剩余参数。函数内部要对参数进行类型检查并返回一个包含所有参数信息的对象。
34.3万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function collectParams(str: string, num?: number, ...bools: boolean[]): {
    stringParam: string;
    numberParam?: number;
    booleanParams: boolean[];
} {
    if (typeof str!=='string') {
        throw new Error('第一个参数必须是字符串');
    }
    if (num!== undefined && typeof num!== 'number') {
        throw new Error('第二个参数如果提供,必须是数字');
    }
    bools.forEach((bool, index) => {
        if (typeof bool!== 'boolean') {
            throw new Error(`布尔值参数列表中第 ${index + 1} 个参数必须是布尔值`);
        }
    });
    return {
        stringParam: str,
        numberParam: num,
        booleanParams: bools
    };
}