typescript 如何设置可能的对象属性类型

vm0i2vca  于 2022-11-18  发布在  TypeScript
关注(0)|答案(1)|浏览(216)

我接口道:

export interface IView {
    "Name": string,
    "Type": number,
    "IsOnlyCurrentWindow": boolean,
    "IsDefault": boolean,
    "IsShared": boolean,
    "Id": string
}

对象属性和方法...

public currentSelectedView: IView | null = null;
public setCurrentView (view: IView) {
    this.currentSelectedView = view;
}
public changeCurrentViewData(changeProperty: keyof IView, value: boolean | string) {
    this.currentSelectedView[changeProperty] = value; // the TS error was occured
}

错误说明

请帮我正确键入
我已经尝试生成另一个类型(keyof IView on string),但再次出现错误

6kkfgxo0

6kkfgxo01#

您需要使用泛型来使参数类型与值类型匹配:

function changeCurrentViewData<T extends keyof IView>(
    changeProperty: T, 
    value: IView[T]
) {
    if (currentSelectedView !== null)
        currentSelectedView[changeProperty] = value;
}

changeCurrentViewData('Name', 'xyz') // ok
changeCurrentViewData('Name', true) // not ok 

changeCurrentViewData('IsOnlyCurrentWindow', true) // ok
changeCurrentViewData('IsOnlyCurrentWindow', 'xyz') // not ok

相关问题