【发布时间】:2018-11-01 13:20:16
【问题描述】:
我正在尝试使用泛型键入组件的道具,但流程没有捕捉到错误。基本上,我想要一个有两个道具fetch 和cb 的组件。无论fetch返回什么类型,都应该是cb的返回类型。
// @flow
import React, { Component } from 'react';
type Props<T> = {
fetch: () => Promise<T>,
cb: T => T,
};
class Client<T> extends Component<Props<T>> {
componentDidMount() {
const { fetch, cb } = this.props;
fetch().then(cb);
}
render() {
return (<div />)
}
}
const App = () => (
<Client
fetch={ () => Promise.resolve(1) }
cb={ n => 'sfd' } />
);
在底部,我将一个函数传递给fetch,该函数解析为number,但cb 返回一个string,并且没有流错误。为什么?
这里是repl。
这甚至不是react 的事情。一个简单的函数将无法检查类型:
const fun = <T>(a: () => T, b: T => T): T => b(a());
fun(() => 2, n => 'qwe');
【问题讨论】:
-
见this 看来流需要
cb参数的类型 -
附上 Alex 的评论:Flow 似乎将
cb道具的类型推断为(string | number) => number。这就是为什么它“需要”为 cb arg 指定的类型。 -
好吧,我使用泛型来避免定义具体类型:) 这是非常基本的类型检查。
标签: javascript reactjs flowtype