使用TypeScript进行反应-类型{...}无法分配给类型'Readonly <s>'

时间:2018-08-02 10:45:53

标签: reactjs typescript interface

我将抽象类用作父React组件,我的应用程序中扩展了许多子组件。

它具有默认状态以及几个类方法,可以选择从扩展组件中覆盖它们。

抽象组件如下:

import * as React from 'react';

export interface StatefulProps {
  observers?: Array<(context: any, state: object) => any>;
}
export interface StatefulState {
  machine: {
    [propName: string]: any;
  };
  name: string;
  value?: any;
}

export default abstract class StatefulComponent<P extends StatefulProps, S extends StatefulState> extends React.Component<P, S> {
  static defaultProps = {
    observers: [],
  };

  state = {
    machine: {},
    name: '',
  };

  abstract generateState(stateName: string, stateParam?: any): object;

  shouldComponentUpdate(_: P, nextState: S) {
    const { name } = this.state;
    if (nextState && nextState.name !== name) {
      return true;
    }
    return false;
  }

  goToState = (stateName: string, stateParam?: any) => {
    const { observers } = this.props;
    this.setState(
      {
        name: stateName,
        machine: this.generateState(stateName, stateParam),
      },
      () => {
        if (observers && observers.length) {
          observers.forEach(observer => {
            if (observer instanceof Function) {
              observer(this, this.state);
            }
          });
        }
      }
    );
  }
}

tslint给状态加了下划线,在悬停时显示以下错误:

Property 'state' in type 'StatefulComponent<P, S>' is not assignable to the same property in base type 'Component<P, S, any>'.
Type '{ machine: {}; name: string; }' is not assignable to type 'Readonly<S>'.

我无法弄清楚我为什么要抱怨...

我对TypeScript还是很陌生,所以完全有理由相信我在做事时是一个完整的布偶,但任何建议/帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

您不能将对象常量分配给通用类型的对象。通用类型约束定义S可以具有的最小属性集,但是可以具有更多属性,其中一些是强制性的,请考虑以下派生类:

class MyStatefulComponent extends StatefulComponent<StatefulProps, StatefulState & { newMandatoryProp: number }> {
    constructor(p: StatefulProps){
        super(p);
        this.state.newMandatoryProp // will be undefined beacuse the base class did not initailize it correctly 
    }
    generateState(stateName: string, stateParam?: any): object { return null as any }
}

您仍然可以使用类型断言来执行此操作,但这不是安全类型:

export default abstract class StatefulComponent<P extends StatefulProps, S extends StatefulState> extends React.Component<P, S> {
    constructor(props: P) {
        super(props);

        this.state = {
            machine: {},
            name: '',
        } as S;
    }
}

您还可以使用抽象方法来创建状态,并将创建完整状态对象的职责传递给派生类。