Javascript Flow:使用connect中的类型扣除道具';类型?

Javascript Flow:使用connect中的类型扣除道具';类型?,javascript,reactjs,redux,react-redux,flowtype,Javascript,Reactjs,Redux,React Redux,Flowtype,简单的例子: const mapStateToProps = (state: State) => ({ error: state.error, // error: ?string }) type Props = { error: number, // wrong type! } class HelloWorld extends Component<Props> { ... } export default connect(mapStateToProps)(Hell

简单的例子:

const mapStateToProps = (state: State) => ({
  error: state.error, // error: ?string
})

type Props = {
  error: number, // wrong type!
}

class HelloWorld extends Component<Props> { ... }

export default connect(mapStateToProps)(HelloWorld)

通过一些黑客攻击,您可以使用函数的返回类型,并将其用作
道具的类型

const mapStateToProps = (state: State): Props => ({
  error: state.error, // error: ?string
})

type Props = {
  error: ?string,
}

class HelloWorld extends Component<Props> { ... }

export default connect(mapStateToProps)(HelloWorld)


然而,我真的很喜欢在这里明确。如果您显式键入
Props
并使
mapstatetops
返回类型
Props
,则非常清楚,并将类型错误保留在正确的位置

const mapStateToProps = (state: State): Props => ({
  error: state.error, // error: ?string
})

type Props = {
  error: ?string,
}

class HelloWorld extends Component<Props> { ... }

export default connect(mapStateToProps)(HelloWorld)
const-mapStateToProps=(state:state):Props=>({
错误:state.error,//错误:?字符串
})
类型道具={
错误:?字符串,
}
类HelloWorld扩展组件{…}
导出默认连接(MapStateTops)(HelloWorld)
这样,如果
状态
错误
类型发生更改,则您将在
MapStateTrops
中获得类型错误,因为该值不再符合
属性
。要解决这一问题,就更容易理解在使用这些值的代码的深处抛出错误的推断类型

它不那么枯燥,但是当事情不匹配时它出现的错误将更容易调试