【问题标题】:How to declare the type in flow of a react redux component with defaultProps?如何使用 defaultProps 在 React Redux 组件的流中声明类型?
【发布时间】:2018-10-04 14:46:33
【问题描述】:

下面的带有类型干扰的示例 1 有效,但我尝试声明导出以改进类型检查失败(请参阅示例 2 和示例 3)。

// @flow

import * as React from 'react'
import { connect } from 'react-redux'

// flow errors below will be the same if Props is an exact type {|...|}
type Props = {
    prop1: number,
    prop2: number,
}

class ExampleClass extends React.Component<Props> {
    static defaultProps = { prop2: 1 }

    render() {
        return this.props.prop1 + this.props.prop2
    }
}

// works, but what is the type of Example1?
export const Example1 = connect(null, null)(ExampleClass)

// Cannot assign connect(...)(...) to Example2 because undefined [1] is incompatible with number [1] in property prop2 of type argument P [2].
export const Example2: React.ComponentType<Props> = connect(null, null)(ExampleClass)
export const example2 = <Example2 prop1={1} />

// Cannot assign connect(...)(...) to Example3 because
// property prop1 is read-only in Props [1] but writable in object type [2] in type argument P [3].
// property prop2 is read-only in Props [1] but writable in object type [2] in type argument P [3].
export const Example3: React.ComponentType<React.ElementConfig<React.ComponentType<Props>>> = connect(null, null)(ExampleClass)
export const example3 = <Example3 prop1={1} />

// Note that this works but I'm looking for a way to declare 
// the type without repeating the list of properties
export const Example2a: React.ComponentType<{prop1: number, prop2?: number}> = connect(null, null)(ExampleClass)

参考这里的代码https://github.com/jacobwallstrom/FlowTypeExampleIssue

【问题讨论】:

    标签: javascript react-redux flowtype flow-typed


    【解决方案1】:

    这应该是一个评论,但我还不能。无论如何,看起来您的示例 repo 使用的是旧版本的 Flow。从 0.89.0 版开始,Flow's support for higher order components (HOC) 已经大大增加。如果您仍然面临此问题或类似问题,我建议您升级到 0.89.0,使用react-redux's flow typings,然后再次调查。

    【讨论】:

      猜你喜欢
      • 2016-07-22
      • 1970-01-01
      • 2019-11-29
      • 2020-10-24
      • 1970-01-01
      • 2022-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多