键入接收对象并更新属性的方法的正确方法是什么?

What is the proper way to type a method that receives an object and updates properties?

我的问题是关于我的 update 方法。正如您在下面看到的,它可以接收一个对象 (newState),并使用 Object.assign() 更新 class 实例属性。我需要告诉 TS 它应该只接受:

我输入的方法是否正确?有更好的//其他方法吗?

另外,在main.ts中,Stateclass实现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());
        }
}

您键入 StateInterface 的方式表明您只需要 newState 中的 StateInterface 键(而不是 State 中可能存在的其他属性)。

如果是这种情况,我会在界面和 class 中输入 update as

update(newState: Partial<StateInterface>): void {
  ...
}

另请注意,这允许替换 StateInterface 中存在的函数,您可能想使用 Omit 来删除不需要的键。