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

如何让TypeScript根据已定义键隐式推断对象值的类型?

问题描述

定义了联合类型SupportedTypes和包含对应转换函数的toData对象,因为给toData显式标注了返回类型为string | number | Date的联合类型,导致_temp函数里做字符串拼接时触发TS2365错误:操作符'+'无法应用于'string | number | Date'类型。

需求是让toData的类型符合{[key in SupportedTypes] : (arg0: string) => FIGURE_IT_OUT}的形式,让TypeScript自动从内部函数推导每个键对应的具体返回类型,不用any。

原始代码:

type SupportedTypes = 'text' | 'currency' | 'date';

const toData : {[key in SupportedTypes] : (arg0: string) => string | number | Date} = {
    text: (str: string) : string => str,
    currency: (str: string) : number => Number(str),
    date: (str: string) : Date => new Date(str)
}

const _temp = () => {
    return toData.text('hello ') + toData.text('everyone')
}

报错信息:

TS2365: Operator '+' cannot be applied to types 'string | number | Date' and 'string | number | Date'.

解决方案

可以用下面两种方法实现自动推导返回类型,同时避免类型错误:

方法1:移除显式类型标注,让TypeScript自动推断

直接删掉toData的类型标注,TypeScript会根据对象里的函数自动识别每个键对应的返回类型:

type SupportedTypes = 'text' | 'currency' | 'date';

// 去掉显式类型,TS会自动推导每个函数的返回值类型
const toData = {
    text: (str: string): string => str,
    currency: (str: string): number => Number(str),
    date: (str: string): Date => new Date(str)
}

const _temp = () => {
    // 此时TS明确知道toData.text返回的是string,拼接操作正常
    return toData.text('hello ') + toData.text('everyone')
}

方法2:用映射类型加泛型,既约束键又自动推导返回值

如果需要强制toData的键只能是SupportedTypes里的值,同时自动推导每个函数的返回类型,可以用泛型工具来实现:

type SupportedTypes = 'text' | 'currency' | 'date';

// 定义工具类型,约束键为SupportedTypes,值是接收string参数的函数
type ToDataMap = {
    [K in SupportedTypes]: (arg0: string) => unknown;
}

// 用泛型让TS自动推断每个函数的具体返回类型
const createToData = <T extends ToDataMap>(map: T) => map;

const toData = createToData({
    text: (str: string): string => str,
    currency: (str: string): number => Number(str),
    date: (str: string): Date => new Date(str)
})

const _temp = () => {
    return toData.text('hello ') + toData.text('everyone')
}

这两种方法都能让TypeScript准确识别toData.text的返回类型是string,解决拼接时的类型错误,而且全程不用any。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 00:13:19