MST

星途 面试题库

面试题:TypeScript 高阶类型在函数重载解析中的应用

编写一个函数 `combine`,它接受两个参数。如果两个参数都是 `number` 类型,则返回它们的和(类型为 `number`);如果两个参数都是 `string` 类型,则返回它们拼接后的字符串(类型为 `string`);否则返回 `null`(类型为 `null`)。请使用 TypeScript 的条件类型和映射类型等高阶技巧,正确定义 `combine` 函数的重载类型,确保类型检查准确无误,同时要考虑到函数内部实现的类型安全性。
50.1万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function combine(a: number, b: number): number;
function combine(a: string, b: string): string;
function combine(a: unknown, b: unknown): number | string | null {
    if (typeof a === 'number' && typeof b === 'number') {
        return a + b;
    } else if (typeof a ==='string' && typeof b ==='string') {
        return a + b;
    } else {
        return null;
    }
}