gpt4 book ai didi

javascript - 流: Use the types from connect to deduct the props' types?

转载 作者:行者123 更新时间:2023-11-30 20:49:46 25 4
gpt4 key购买 nike

简单的例子:

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)

我的问题:

  1. Not DRY: error 来自于 Redux 的状态并且它的类型已经在 State 中指定了
  2. 应该是 ?string 但我们可以放任何东西,可能会导致错误

有什么方法可以告诉 Flow“这个 prop 来自 state,所以采用相同的类型”?

有点像

type Props = PropsFromConnect // { error: ?string }

?

最佳答案

通过一些技巧,您可以使用函数的返回类型,并将其用作 Props 的类型。

https://github.com/facebook/flow/issues/4002#issuecomment-344255679


不过,我真的很想在这里说清楚。如果您显式键入 Props 并使 mapStateToProps 返回类型 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)

这样,如果 Stateerror 类型发生变化,那么您将在 mapStateToProps 中得到一个类型错误,因为该值不再符合 Prop 。解决这个问题比尝试理解推断类型在使用这些值的代码深处引发错误要容易得多。

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

关于javascript - 流: Use the types from connect to deduct the props' types?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48307359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com