我想要一个只接受 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'
。我希望有效载荷只接受我在顶部声明的状态。
答案 0 :(得分:1)
如果我理解正确,您希望使用单个函数而不是 toggle
、success
和 error
?
这样的事情对你的情况有用吗?
class DialogStore {
// ...
update(payload: StateToUpdate) {
Object.keys(payload).forEach((property) => {
this[property] = payload[property];
});
}
}
type StateToUpdate = Partial<Pick<DialogStore, 'status' | 'type' | 'content'>>
为了避免 TS 错误,您可以在 "suppressImplicitAnyIndexErrors": true
中完全禁用标志 tsconfig.json
或使用一些类型转换:
Object.keys(payload).forEach((property) => {
(this as any)[property] = payload[property as keyof StateToUpdate];
});
我认为目前没有简单的方法可以减轻 TS 中的此类错误,不过我可能错了。