I have a question regarding the update method in my code. In the function below, it takes an object called newState and uses Object.assign() to update the properties of the class instance. I want TypeScript to only allow:
- An object as input
- Properties that are keys of the State Class
- Values for those properties that match the respective types
Did I correctly define this method? Is there a better or alternative approach to achieve this?
Furthermore, in main.ts, when implementing StateInterface on the State class, the TypeScript compiler shows an error stating that the parameter newState in the update method is implicitly any. Shouldn't it be getting type information from 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());
}
}