我的问题是关于我的更新方法。正如您在下面看到的,它可以接收一个对象(newState),并使用 Object.assign() 更新类实例属性。我需要告诉 TS 它应该只接受:
- 一个东西
- 作为 State 类的键的属性
- 那些属性的值是属性的正确类型。
我是否正确输入了此方法?有更好的//其他方法吗?
另外,在 main.ts 中,State 类实现 StateInterface 上,TS 编译器有一个错误,即 update (newState) 的参数隐式为 any。它不应该从 types.d.ts 接收类型信息吗?:
/// types.d.ts
export interface StateInterface {
user: User;
fileList: DirectoryResponse;
selectedFiles: Array<SelectedFile>;
currentDir: string;
response: APIResponse;
menu: Menu;
dialog: Dialog;
history: object;
update: <P extends StateInterface, T extends keyof StateInterface>(newState: { [key in T]: P[T]}) =>
Promise<void>;
syncPage: () => void;
}
/// main.ts
class State implements StateInterface {
user: User;
fileList: DirectoryResponse;
selectedFiles: SelectedFiles;
currentDir: string;
response: APIResponse;
menu: Menu;
dialog: Dialog;
history: History;
constructor(user: User, fileList: DirectoryResponse, selected: SelectedFiles, currentDir: string, response: APIResponse, menu: Menu, dialog: Dialog, history: History = { forward: false, back: false }) {
this.user = user;
this.fileList = fileList;
this.selectedFiles = selected.slice();
this.currentDir = currentDir;
this.response = response || { fileResults: [], folderResults: [] };
this.menu = menu || { location: '', type: 'folder' };
this.dialog = dialog || { type: "", state: false };
this.history = history;
}
get dir() {
return this.currentDir.slice(1).split('/');
};
async update(newState): Promise<void> {
^^^^^^^^ (implicit any)
if (newState) {
Object.assign(this, newState);
}
this.fileList = await readDir(this.currentDir).then(r=>r.json());
}
}