简体   繁体   中英

Get value from object by interface property?

I have a custom class:

class CalendarThematicPlanModel extends FilterMethods<ICalendarThematicPlanShort> implements IModel<W> {
    public constructor(public model?: ICalendarThematicPlanShort) {
        super();
    }

    public validField<ICalendarThematicPlanShort, K extends keyof ICalendarThematicPlanShort>(key:K) { 
        this.model[key];
    }
}

I tied to be sure that passed key in method validField(key) is definitely exists in interface ICalendarThematicPlanShort and in this.model .

The problem is you define a generic parameter with the same name as the interface. And thus, K is a key of that generic type parameter and not of your interface:

class CalendarThematicPlanModel extends FilterMethods<ICalendarThematicPlanShort> implements IModel<W> {
    public constructor(public model?: ICalendarThematicPlanShort) {
        super();
    }

    public validField<K extends keyof ICalendarThematicPlanShort>(key:K) { 
        this.model[key];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM