TS2322:输入&#39; {ready:false; session:null; }&#39;不能分配给&#39; Readonly <s&=“”withauthstate =“”>&#39;

时间:2018-03-14 08:43:03

标签: javascript typescript reactxp

我有以下界面:

export interface withAuthState {
  ready: boolean,
  session: any
}

以下HOC:

const withAuth = <P extends withAuthProps, S extends withAuthState>(
  WrappedComponent: new (props: P) => RX.Component<P, S>
) =>    class WithAuth extends RX.Component<P & withAuthProps, S & withAuthState> {
        constructor(props) {
          super(props);

          this.state = {
            ready: false,
            session: null
          };
        }
    }

我无法在构造函数中设置状态。错误是:

TS2322: Type '{ ready: false; session: null; }' is not assignable to type 'Readonly<S & withAuthState>'.

我在这里明显遗漏了一些东西,但我不知道是什么。

任何帮助表示赞赏。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

问题在于州可能有其他属性,您无法初始化,因为您在HOC中不了解它们。请考虑以下事项:

class MyComponent extends RX.Component<withAuthProps, withAuthState & { myStateProp: number }>{}    
const MyComponentWithAuth = withAuth(MyComponent);
let comp = new MyComponentWithAuth({});
// myStateProp does not exist on state because you did not initialize it in your HOC even though the property is required
comp.state.myStateProp 

如果你对这种行为没问题,你可以在初始化状态时使用类型断言:

this.state = {
    ready: false,
    session: null
} as S & withAuthState;