如何在 flowjs 中描述通用组件导出的类型
How to describe type for a generic component export in flowjs
我正在将代码升级为类型优先,并坚持需要通过 flowjs 注释显式声明通用反应组件的类型
// @flow
import * as React from 'react';
type P<TArg> = {
items: TArg[],
onSelect: (props: TArg) => void
}
type Item = {
key: string
}
class Autocomplete<TElem: Item> extends React.Component<P<TElem>> {
}
//its external function provided via import, i put it here for simplicity
function woodoo<F>(v: F): F {
return v
}
如果我尝试导出调用函数的结果:
export default woodoo(Autocomplete)
我会得到以下错误:
Cannot build a typed interface for this module. You should annotate the exports of this module with types. Cannot determine the type of this call expression. Please provide an annotation, e.g., by adding a type cast around this expression.Flow(signature-verification-failure)
如果我尝试通过组件导出它:
export default (woodoo(Autocomplete): Autocomplete)
我会得到以下错误:
Cannot use Autocomplete
[1] without 1 type argument.Flow(missing-type-arg)
我知道导出应该更像
export default (woodoo(Autocomplete): React$ComponentType<????>)
但我不知道要在角背中放入什么才能实现正确的打字。
使组件协变而不是通用是无效的,因为在 onSelect
函数中传递的预期值与通过 items
属性 提供的预期值完全相同,并且协方差的使用不会产生与使用泛型相同的严格程度。
最简单的方法是将鼠标悬停在组件上,检查它的类型,然后在导出处填写。
随便你试试:
export default (woodoo(Autocomplete): React.Element<typeof Autocomplete>)
你试过吗?
export default (woodoo(Autocomplete): typeof Autocomplete);
我通过 vscode 使用快速修复功能直接得到了这个答案
我正在将代码升级为类型优先,并坚持需要通过 flowjs 注释显式声明通用反应组件的类型
// @flow
import * as React from 'react';
type P<TArg> = {
items: TArg[],
onSelect: (props: TArg) => void
}
type Item = {
key: string
}
class Autocomplete<TElem: Item> extends React.Component<P<TElem>> {
}
//its external function provided via import, i put it here for simplicity
function woodoo<F>(v: F): F {
return v
}
如果我尝试导出调用函数的结果:
export default woodoo(Autocomplete)
我会得到以下错误:
Cannot build a typed interface for this module. You should annotate the exports of this module with types. Cannot determine the type of this call expression. Please provide an annotation, e.g., by adding a type cast around this expression.Flow(signature-verification-failure)
如果我尝试通过组件导出它:
export default (woodoo(Autocomplete): Autocomplete)
我会得到以下错误:
Cannot use
Autocomplete
[1] without 1 type argument.Flow(missing-type-arg)
我知道导出应该更像
export default (woodoo(Autocomplete): React$ComponentType<????>)
但我不知道要在角背中放入什么才能实现正确的打字。
使组件协变而不是通用是无效的,因为在 onSelect
函数中传递的预期值与通过 items
属性 提供的预期值完全相同,并且协方差的使用不会产生与使用泛型相同的严格程度。
最简单的方法是将鼠标悬停在组件上,检查它的类型,然后在导出处填写。
随便你试试:
export default (woodoo(Autocomplete): React.Element<typeof Autocomplete>)
你试过吗?
export default (woodoo(Autocomplete): typeof Autocomplete);
我通过 vscode 使用快速修复功能直接得到了这个答案