Search code examples
javascripttypescripttypeskeyof

How to set the type of possible object properties


I have an interface:

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

object properties and methods...

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
}

the error says that enter image description here

please help me to type correctly

I already tried to make another type (keyof IView on string), but again i get error enter image description here


Solution

  • You need to use a generic to make the param type match the value type:

    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