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

如何为TypeScript的foo函数添加泛型注解以精准推断返回类型?

解决方案:用泛型+条件类型实现精准类型推断

先看原代码的问题:

class Foo1 {
  a: number = 42
}

class Foo2 {
  a: string = "foobar"
}

type Format = "foo1" | "foo2"

function foo(format: Format) {
  if (format === "foo1") return new Foo1();
  return new Foo2()
}

const f = foo("foo1"); // 类型被推断为 Foo1 | Foo2,不符合预期

可以通过泛型结合条件类型,让TypeScript根据传入的参数值精准推断返回类型,修改后的代码如下:

class Foo1 {
  a: number = 42
}

class Foo2 {
  a: string = "foobar"
}

type Format = "foo1" | "foo2";

// 定义参数值到返回类型的映射关系
type FormatToType<T extends Format> = 
  T extends "foo1" ? Foo1 : Foo2;

function foo<T extends Format>(format: T): FormatToType<T> {
  if (format === "foo1") return new Foo1() as FormatToType<T>;
  return new Foo2() as FormatToType<T>;
}

const f = foo("foo1"); // 现在类型被精准推断为 Foo1
const g = foo("foo2"); // 类型被精准推断为 Foo2

关键说明:

  • 泛型T被约束为Format类型,确保传入的参数只能是"foo1"或"foo2"。
  • FormatToType是条件类型,根据T的具体值返回对应的类类型,建立参数和返回值的类型关联。
  • 函数内部的类型断言as FormatToType<T>是必要的,因为TypeScript编译器无法自动将分支的具体返回值和泛型条件类型做匹配,手动断言可以消除类型报错。

除了泛型方式,也可以用函数重载实现类似效果,但泛型写法更简洁且能统一逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 02:06:24