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

如何根据参数对象属性类型切换TypeScript函数返回类型?

解决TypeScript根据locale属性类型切换函数返回类型的问题

需求是:根据传入对象的locale属性类型(string或undefined),让getItem函数返回对应类型——当locale为string时返回string,当locale不存在或为undefined时返回多语言对象WithLocale。之前的两种写法都导致编译器推断返回类型为never,且不想通过新增布尔属性实现,以下是可行方案:

问题分析

  • 第一种写法中,typeof options['locale']的类型是string | undefined,条件类型的两个分支(extends string和extends undefined)都无法匹配这个联合类型,因此最终返回never。
  • 第二种泛型写法中,函数内部的返回值无法与泛型的条件类型建立直接关联,编译器无法推导返回值符合GetItemReturnType<T>的约束,导致报错。

解决方案:函数重载

函数重载能直接根据不同的参数类型指定对应的返回类型,是处理这类场景最直观的方式:

type WithLocale = {
    en: string
    fr: string
    de: string
}

type WithoutLocale = string

// 重载签名1:传入带明确string类型locale的参数,返回string
function getItem(options: { locale: string }): WithoutLocale;
// 重载签名2:传入不带locale或locale为undefined的参数,返回WithLocale
function getItem(options?: { locale?: undefined }): WithLocale;
// 实现签名(仅用于内部逻辑,不对外暴露)
function getItem(options?: { locale?: string }) {
    if (options?.locale !== undefined && typeof options.locale === 'string') {
        return 'test string';
    } else {
        return {
            en: 'test string en',
            fr: 'test string fr',
            de: 'test string de',
        };
    }
}

调用示例

// 返回类型为WithoutLocale(string)
const localizedStr = getItem({ locale: 'fr' });
// 返回类型为WithLocale
const multiLangObj1 = getItem();
const multiLangObj2 = getItem({ locale: undefined });

这种写法让编译器能精准识别不同参数对应的返回类型,完全满足需求且无需额外布尔属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 11:21:27