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

泛型函数返回类型存入对象后丢失类型信息的问题

解决TypeScript泛型函数返回类型存入对象后丢失类型信息的问题

首先咱们拆解下问题根源:你用ReturnType<typeof thinger>的时候,因为thinger是泛型函数,在没指定具体泛型参数的情况下,TypeScript没法推断出它的具体返回类型,最终会把ThingHolder里的thing解析成unknown。这自然就导致你访问myThingHolder.thing.a时会报错——毕竟unknown类型上没有a属性嘛。

下面给你几个可行的解决方案:

方案一:让接口ThingHolder变成泛型接口

通过给接口添加泛型参数,在使用时传入具体类型,就能完整保留类型信息:

interface ThingHolder<T> {
  thing: T;
}

const myThingHolder: ThingHolder<{ a: string }> = {
  thing: thinger({ a: "lol" }),
};

// 现在可以正常访问a属性了
myThingHolder.thing.a;

方案二:复用已推断的变量类型

既然你直接调用thinger得到的thing已经有正确的类型推断,那可以直接用typeof thing来定义接口里的类型:

const thing = thinger({ a: "lol" });

interface ThingHolder {
  thing: typeof thing;
}

const myThingHolder: ThingHolder = {
  thing,
};

myThingHolder.thing.a; // 正常访问无压力

方案三:给ReturnType明确指定泛型参数

如果你不想改动接口结构,也可以直接在ReturnType里给thinger指定具体的泛型参数,明确返回类型:

interface ThingHolder {
  thing: ReturnType<typeof thinger<{ a: string }>>;
}

const myThingHolder: ThingHolder = {
  thing: thinger({ a: "lol" }),
};

myThingHolder.thing.a; // 类型正常识别

方案四:让TypeScript自动推断对象类型(最简洁)

如果不需要提前定义接口,直接让TypeScript自动推断myThingHolder的类型是最省事的:

const myThingHolder = {
  thing: thinger({ a: "lol" }),
};

// TypeScript会自动推断出myThingHolder.thing的类型是{ a: string }
myThingHolder.thing.a;

总结来说,核心就是要让TypeScript能捕获到thinger返回的具体类型,不管是通过泛型传递、复用已有类型、明确指定参数还是自动推断,都能解决类型丢失的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:28:56