带约束的通用类型不能分配给通用接口

我在TypeScript 2.4.2中的泛型类中出现错误,其约束与不太严格的接口不兼容 . 我收到以下错误:

ts / components / Schedule.ts(37,13):错误TS2322:输入'{personWeekView:PlanItemScheduleView; projectWeekView:PlanItemScheduleView; r ...'不能分配给'Map'类型 . 属性“personWeekView”与索引签名不兼容 . 类型'PlanItemScheduleView'不能分配给'IPlanItemScheduleView'类型 . 属性'onAddedItem'的类型不兼容 . 类型'(item:T,initial:boolean)=> void'不能赋值为'(item:T,initial:boolean)=> void' . 参数'item'和'item'的类型不兼容 . 类型'T'不能分配给'PlanItem'类型 . ts / views / PlanItemScheduleView.ts(2,18):错误TS2420:类'PlanItemScheduleView'错误地实现了接口'IPlanItemScheduleView' . 属性'onAddedItem'的类型不兼容 . 类型'(item:T,initial:boolean)=> void'不能赋值为'(item:T,initial:boolean)=> void' . 参数'item'和'item'的类型不兼容 . 类型'T'不能分配给'PlanItem'类型 . ts / views / PlanItemScheduleView.ts(99,79):错误TS2345:类型'this'的参数不能分配给'IControllerListener'类型的参数 . 类型'PlanItemScheduleView'不能分配给'IControllerListener'类型 . 属性'onAddedItem'的类型不兼容 . 类型'(item:T,initial:boolean)=> void'不能赋值为'(item:T,initial:boolean)=> void' . 参数'item'和'item'的类型不兼容 . 类型'T'不能分配给'PlanItem'类型 .

Interfaces

namespace Planning {
    export interface IPlanItemScheduleView extends IView, IControllerListener<IPlanItem> {
        setTimespan(timespan: Timespan): void;
        getName(): string;
    }
}
namespace Planning {
    export interface IControllerListener<T> {
    /**
     * Notifies the listener that an item is added to the cache so it can add it to its view.
     * 
     * @template T
     * @param {T} item
     * @param {boolean} initial
     * 
     * @memberOf IControllerListener
     */
    onAddedItem<T>(item: T, initial: boolean): void;
    }
}

namespace Planning {
    export class PlanItemScheduleView<T extends PlanItem> implements IPlanItemScheduleView {

        public onAddedItem<T extends PlanItem>(item: T, initial: boolean): void {
            // implementation that needs properties on PlanItem
        }
    }
}

PlanItem是一个抽象的基类,由一些实际的实现继承 . 我有一些不同类型的viwes,我这样构建:

// Create the different views
  this._views = {
            personWeekView: new PlanItemScheduleView<Person>(this._options, this._logger, this),
            projectWeekView: new PlanItemScheduleView<Project>(this._options, this._logger, this),
            resourceWeekView: new PlanItemScheduleView<Resource>(this._options, this._logger, this),
        };

我以为我之前在另一个版本的tsc中进行了编译,但我可能会弄错 . 我怎样才能解决这个问题?

回答(1)

2 years ago

您不需要 onAddedItem 上的泛型参数,如果希望 onAddedItem 采用与类相同的参数类型,则可以使用class参数 . 你可以使 IPlanItemScheduleView 泛型,以便将 PlanItemScheduleView 类型参数传递给 IControllerListener

export interface IControllerListener<T> {
  onAddedItem(item: T, initial: boolean): void;
}
export interface IPlanItemScheduleView<T extends IPlanItem>  extends IControllerListener <T> {

}
export class PlanItemScheduleView<T extends PlanItem> implements IPlanItemScheduleView<T> {
  public onAddedItem(item: T, initial: boolean): void {
      // implementation that needs properties on PlanItem
  }
}

注意:编辑时要考虑到反馈 .