如何使用defaultProps声明react redux组件的流类型?

问题描述 投票:3回答:1

下面的示例1与类型干扰有效但我尝试声明导出以改进类型检查失败(参见Example2和Example3)。

// @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个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.