react-redux connect装饰器导致的ts props声明出现问题?

interface iCustomProps { /* ... */ }

function mapStateToProps(state: StoreState): iCustomProps { /* ... */ }

@connect(mapStateToProps, mapDispatchToProps)
export default class TestCompo extends React.Component { /* ... */ } // [1]

[1]: 如果这儿不标识props的类型的话,以后使用this.props总会显示红波浪线,搞得每个用到的地方都需要手动标识props类型,很烦;
可是如果这里标识props类型的话,又会导致引用该组件时会提示你还有属性没加上去,很烦。。。


// 栗子1

@connect(mapStateToProps, mapDispatchToProps)
export default class TestCompo extends React.Component {
    func() {
        // warning: 编译器认为没有这个属性
        const { this.customProp } = this.props
        // 必须这么写
        // const { this.customProp } = this.props as iCustomProps
    }
}

// 栗子2

@connect(mapStateToProps, mapDispatchToProps)
export default class TestCompo extends React.Component<iCustomProps> { /* ... */ }

// warning: 编译器认为你没有写全 iCustomProps 列出来的属性
// 可问题时那些属性是redux映射出来的啊,编译器认不出来吗?
// 还是说是我的编辑器有问题?
<TestCompo />
阅读 4.5k
2 个回答

试试这样写

export interface iCustomProps{
  tips: React.ReactNode;
  src: string;
  style?: React.CSSProperties;
}

export default class TestCompo extends React.Component<iCustomProps, any> {
  constructor(props: IAvatarItemProps);
}

这个是官方自己好几年都没解决的问题:点击这里查看

只能这样写了
export default connect(mapStateToProps, mapDispatchToProps)(TestCompo);

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题