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 }
please help me to type correctly
I already tried to make another type (keyof IView on string), but again i get error
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