簡體   English   中英

ReactJs / Typescript:如何擴展state接口

[英]ReactJs / Typescript: How to extend state interface

我有以下內容:

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)
  }
}

如何使用EditViewState並使用來自具體 class 的S擴展它?

現在我有一個使用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" })
  }
}

有了這個,一切都完美無缺。 具體的 class 現在可以自動完成EditViewState的狀態和它自己的狀態S

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM