Skip to content
Advertisement

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

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement