MST

星途 面试题库

面试题:TypeScript函数定义基础规则应用

请定义一个TypeScript函数,该函数接受两个数字参数,返回它们的和。同时,对函数的参数和返回值进行类型标注,并展示如何使用函数重载实现接受不同类型参数(如两个字符串参数拼接后返回字符串)。
15.9万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 函数重载声明1:接受两个数字参数,返回数字
function add(a: number, b: number): number;
// 函数重载声明2:接受两个字符串参数,返回字符串
function add(a: string, b: string): string;

// 函数实现,根据重载声明来决定具体行为
function add(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;
    }
    throw new Error('Unsupported parameter types');
}

// 使用示例
const numResult = add(1, 2);
const strResult = add('Hello, ', 'world');