【问题标题】:Is it possible to infer the type of component properties based on parent component?是否可以根据父组件推断组件属性的类型?
【发布时间】:2018-01-26 07:37:07
【问题描述】:

我有这个容器

export interface State {
  email: string
}

const mapStateToProps = (state: State) => ({
  email: state.email,
})

const mapDispatchToProps = (dispatch: Dispatch<Action>) => ({
  onChange: (name: string, value: string) => dispatch(/*...*/),
})

export default connect(mapStateToProps, mapDispatchToProps)(Login)

还有这个组件

export interface LoginProps {
  email: string
  onChange: (name: string, value: string) => void
}

const Login = (props: LoginProps) => (
  <p>Render something here</p>
)

有没有办法根据Container 定义推断登录属性的类型,这样我就不必手动定义LoginProps 了?

【问题讨论】:

  • 您能否举例说明您希望代码的外观?
  • 理想情况下,我希望什么都不指定,只是推断它

标签: reactjs typescript redux react-redux


【解决方案1】:

connect 有很好的类型定义,因此可以推断传递给被包装组件的 props 的类型。如果你这样写容器/组件...

export interface State {
  email: string
}

const stateToProps = (state: State) => ({
    email: state.email
  })

const dispatchToProps = (dispatch: Dispatch<Action>) => ({
    onChange: (name: string, value: string) => dispatch(/*...*/)
})

const BlahBlah = connect(stateToProps, dispatchToProps)(({ email, onChange }) => (
    <div />
));

emailonChange 输入正确,无需额外注释。

但是,当你单独编写Login组件时,没有类型注解...

const Login = (props) => (
  <p>Render something here</p>
)

无法推断props 的类型。这是因为除了将Login 传递给connect 之外,您还可以直接调用它。例如,我可以写在一个组件中:

render() {
    return (
        <Login unrelated="a string" typescript="cool" />
    );
}

如果 Login 组件上没有注释,编译器就无法知道 Login 的哪个调用(连接的,或者我的直接渲染)提供了正确的 props。如果没有注解,那么编译器只能将 props 输入为 any,因此我们失去了类型安全性。

【讨论】:

  • 非常感谢,很有道理
猜你喜欢
  • 2021-01-15
  • 1970-01-01
  • 2022-12-18
  • 1970-01-01
  • 2016-05-02
  • 2022-11-03
  • 2018-12-07
  • 2020-03-09
  • 2020-09-23
相关资源
最近更新 更多