You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据可选参数是否传入匹配TypeScript函数对应返回类型

解决方案

你可以通过两种TypeScript语法实现基于入参自动推导返回类型的需求:


方案1:函数重载(推荐,可读性最高)

直接声明两种入参场景对应的返回类型,TypeScript会自动匹配推导:

type base = {
    a: string;
};

type base_plus = {
    foo: string;
};

// 重载签名1:传入param时返回base_plus
function get(param: number): base_plus;
// 重载签名2:不传param时返回base
function get(): base;
// 兼容所有重载的实现逻辑
function get(param?: number) {
    const newBase: base = { a: '1' };

    if (param) {
        return { ...newBase, foo: 'bar' } as base_plus;
    }
    return newBase;
}

// 验证效果
const a = get(1); // 自动推导为base_plus类型
const b = get(); // 自动推导为base类型

方案2:泛型+条件返回类型(单签名实现)

如果偏好单函数签名的写法,可以配合泛型和条件类型实现:

type base = {
    a: string;
};

type base_plus = {
    foo: string;
};

// 泛型T匹配入参param的类型,根据T的类型推导返回值类型
const get = <T extends number | undefined = undefined>(param?: T): T extends number ? base_plus : base => {
    const newBase: base = { a: '1' };

    if (param) {
        return { ...newBase, foo: 'bar' } as any;
    }
    return newBase as any;
};

// 验证效果和重载方案完全一致
const a = get(1); // base_plus类型
const b = get(); // base类型

注:实现部分的as any仅用于绕过TypeScript对条件返回值的内部推导校验,不会影响外部调用时的类型安全性。


内容的提问来源于stack exchange,提问作者sshmaxime

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 13:18:03