【问题标题】:Possible to use Generics defined in Generic definition可以使用泛型定义中定义的泛型
【发布时间】:2018-04-18 17:25:27
【问题描述】:

我正在尝试使用在类的泛型定义中定义的泛型:

type Foo<T : BoundType> = {
    bar : T
}

class Class<F : Foo<T : BoundType>> {
    method(arg : T) { ... }
}

Flow 抱怨 Class&lt;F : Foo&lt;T : BoundType&gt;&gt; 的语法

有没有办法在类中使用 Foo 中使用的 T 类型?以下工作,但我试图消除重复类型两次的需要:

type Foo<T : BoundType> = {
    bar : T
}

class Class<T : BoundType, F : Foo<T>> {
    method(arg : T) { ... }
}

let x = new Class<ConcreteType, Foo<ConcreteType>>;

【问题讨论】:

  • 可以添加投诉吗?
  • 从第一块代码开始:class Class&lt;F : Foo&lt;T : BoundType&gt;&gt; { ^ T. Unexpected token :
  • 如果你能在flow.org/try 中给出一个清晰的例子会更容易理解。实际上,您的示例 new Class&lt;ConcreteType, Foo&lt;ConcreteType&gt;&gt;; 首先是无效的,而且我们没有 ConcreteTypeBoundType 的示例。
  • 请澄清类型之间的预期关系。也许你应该给我们一个简单数据的例子,显示你的期望
  • 您上面的代码看起来像 TypeScript,不会在浏览器中运行。您需要将其“编译”为 JavaScript。

标签: javascript flowtype


【解决方案1】:

您可以使用Existential Type (*) 告诉Flow 推断泛型类型参数,并使用$ElementType 来“查询”bar 属性类型:

type Foo<T : BoundType> = {
    bar : T
}

class TestClass<F : Foo<*>> {
    method(arg : $ElementType<F, 'bar'>) { }
}

declare var c: TestClass<Foo<ConcreteType>>;

Try it here

** 可能有更好的方法来获取泛型类型参数的类型,而不是查询bar 属性类型。

*** 将Class 重命名为TestClass,因为Class 是流的实用程序之一,所以我建议您不要使用它作为名称。

【讨论】:

    猜你喜欢
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    • 2011-09-15
    相关资源
    最近更新 更多