首页 > 解决方案 > 调用泛型函数时使 Flow 需要类型

问题描述

如何使 Flow 要求在调用函数时指定泛型类型?

// @flow strict

type Person = {
  _id: string,
  name: string,
  age: number,
}

type WrapperObj = {
  genericFn<T>(string): T | null,
}

function testFunc (obj: WrapperObj, name: string) {
  // Goal: have flow produce error on the following line because generic is missing...
  const jack = obj.genericFn(name)
  if (jack) {
    // ...so that this line produces an error
    jack.height
  }
}

试试 Flow 链接

如果我以以下任何一种方式在第 15 行提供类型:

const jack = obj.genericFn<Person>(name)

const jack: Person | null = obj.genericFn(name)

...然后 Flow 正确地在第 18 行给出了我所期望的错误。

Flow 似乎在推断类型T,因为any实际上我们希望它抱怨缺少类型。

标签: javascriptflowtype

解决方案


推荐阅读