javascript - ReactJs/Typescript: Cách mở rộng giao diện state
Tôi có những điều sau:
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)
}
}
Làm thế nào tôi có thể sử dụng EditViewState và mở rộng nó với S mà đến từ lớp cụ thể?
Câu trả lời #1
Hiện tại tôi có một giải pháp tạm thời bằng cách sử dụng 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" })
}
}
Với điều đó, mọi thứ hoạt động hoàn hảo. Lớp cụ thể bây giờ có tự động hoàn thành cho các trạng thái của EditViewState và các trạng thái của chính nó S.
