将 React defaultProps 与 connect 结合使用时出现 Typescript 错误

Ari*_*ion 5 typescript reactjs redux react-redux

我正在尝试添加defaultPropsMyComponent,然后将其连接到 redux. 为此,我使用Partial<MyComponentProps>as defaultPropss 类型。然而,Typescript 正在抱怨

属性类型bar在 中是可选的Partial<MyComponentProps>,但在 中是必需的{ bar: number }

我想弄清楚为什么会发生这种情况,以及什么是好的解决方案。这是代码:

interface MyComponentProps {
  foo: string;
  bar: number;
}

class MyComponent extends React.PureComponent<MyComponentProps, void> {
  public static defaultProps: Partial<MyComponentProps> = {
    foo: "hello"
  };

  public render() {
    return null;
  }
}

function mapStateToProps(state: any) {
  return {
    bar: 7
  };
}

connect(mapStateToProps)(MyComponent);
Run Code Online (Sandbox Code Playgroud)

Typescript 正在MyComponent抱怨connect(mapStateToProps)(MyComponent);

投射defaultPropsMyComponentProps,或mapStateToProps(state: any): Partial<MyComponentProps>同时使用两者,但这似乎应该是开箱即用的。defaultProps是官方的 React 模式。