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

在Facebook Flow中能否用一种类型表示多个类类型?

解决Flow中Class构造函数报错问题

正确类型定义方案(推荐)

你可以用泛型实现类型安全约束,避免重复写联合类型。通过泛型T约束为Animal,让函数接收Class<T>类型的参数,返回值会自动推导为T的实例:

//@flow strict

interface Animal {
  eat(): void,
}

class Dog implements Animal {
  constructor() { }
  eat() { }
  bark() { }
}

class Cat implements Animal {
  constructor() { }
  eat() { }
  meow() { }
}

foo(Dog); // 返回Dog实例
foo(Cat); // 返回Cat实例

function foo<T: Animal>(c: Class<T>): T {
  return new c();
}

这个方案既能自动推导返回类型,又不用重复定义联合类型,完全匹配你的需求。

跳过类型检查的应急方案

如果暂时不想调整类型结构,可使用Flow的// $FlowFixMe注释跳过该位置的检查:

function foo(c: Class<Animal>) {
  // $FlowFixMe 跳过构造函数类型检查
  return new c();
}

也可以通过类型断言将c转为兼容构造函数的类型:

function foo(c: Class<Animal>) {
  return new (c: Class<{new(): Animal}>);
}

不过这类方式会损失部分类型安全性,仅建议临时应急使用。

内容的提问来源于stack exchange,提问作者d.k

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 18:32:34