MST

星途 面试题库

面试题:TypeScript函数重载与联合类型的深度应用

实现一个TypeScript函数 `combineValues`,它支持两种调用方式:第一种是接收两个数字参数,返回它们的和;第二种是接收两个字符串参数,返回它们拼接后的结果。请使用函数重载来实现这个功能,并正确处理可能出现的联合类型相关的类型检查问题。
19.4万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function combineValues(a: number, b: number): number;
function combineValues(a: string, b: string): string;
function combineValues(a: number | string, b: number | string): number | string {
    if (typeof a === 'number' && typeof b === 'number') {
        return a + b;
    } else if (typeof a ==='string' && typeof b ==='string') {
        return a + b;
    } else {
        throw new Error('Invalid argument types');
    }
}