ReactJs / Typescript: How to extend state interface

Viewed 146

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?

1 Answers

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.

Related