mobx 中的动态状态更新反应打字稿

Dynamic state update in mobx react typescript

我想要一个只接受在 mobx 中声明的状态的函数。我目前有这个代码。

class DialogStore {
    status: boolean = false;
    title: string = '';
    content: string = '';
    btnText: string = ''; 
    icon: JSX.Element | string = '';
    type: 'success' | 'error' = 'success';

    constructor() {
        makeAutoObservable(this);
    }

    toggle(status: boolean) {
        this.status = status
    }

    success(content: string) {
        this.type = 'success';
        this.status = true;
        this.content = content;
    }

    error(content: string) {
        this.type = 'error';
        this.status = true;
        this.content = content;
    }
}

我想添加这样的动态函数:

update(payload: TypeOfState) {
    Object.keys(payload).forEach(property => {
        this[property] = payload[property];
    })
}

我试图将 any 作为我的负载类型,但它给我这个错误 Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'DialogStore'。我希望payload只接受我在顶部声明的状态。

如果我对你的理解是正确的,你想要单一功能而不是 togglesuccesserror

这样的事情对你的情况有用吗?

class DialogStore {
  // ...

  update(payload: StateToUpdate) {
    Object.keys(payload).forEach((property) => {
      this[property] = payload[property];
    });
  }
}

type StateToUpdate = Partial<Pick<DialogStore, 'status' | 'type' | 'content'>>

为避免 TS 错误,您可以在 tsconfig.json 中完全禁用标志 "suppressImplicitAnyIndexErrors": true 或使用一些类型转换:

    Object.keys(payload).forEach((property) => {
      (this as any)[property] = payload[property as keyof StateToUpdate];
    });

我认为现在没有简单的方法来减轻 TS 中的此类错误,不过我可能是错的。