简体   繁体   中英

ReactJs / Typescript: How to extend state interface

I have the following:

interface EditViewState<T> {
    entity?: T;
}

abstract class EditView<T, P, S> extends React.Component<P, EditViewState<T> & S> {

  constructor(props: P, ctx: any) {
      super(props, ctx);
      this.state = {
          mode: "loading" // Type '{ entity: null; }' is not assignable to type 'Readonly<EditViewState<T> & S>'.ts(2322
      }
  }
 componentDidMount() {
      this.setState({ mode: "show" }) // Type '"show"' is not assignable to type '("loading" & S["mode"]) | ("show" & S["mode"]) | ("edit" & S["mode"])'.ts(2345)
  }
}

How can I use the EditViewState and extend it with S which is coming from the concrete class?

For now I have a workaround by using Exclude

abstract class EditView<T, P, S> extends React.Component<P, Exclude<EditViewState<T> & S, keyof S>> {

 constructor(props: P, ctx: any) {
      super(props, ctx);
      //@ts-ignore https://github.com/microsoft/TypeScript/issues/38947
      this.state = {
          mode: "loading"
      }
  }

  componentDidMount() {
      this.setState({ mode: "show" })
  }
}

With that everything works perfect. The concrecte class now has the auto completion for the states of EditViewState and it's own states S .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM