#typescript #generics #inheritance #constraints #extend
#typescript #общие #наследование #ограничения #расширить
Вопрос:
У меня есть два класса. Абстрактный суперкласс:
export abstract class Entity<IEntityData> {
protected readonly _source: IEntityData; // TODO: replace with private
protected constructor(entityData: IEntityData) { this._source = entityData }
get source(): IEntityData { return this._source }
}
и унаследованный класс:
import { Entity } from './entity/entity';
interface ITestData {
foo: string;
bar: number;
}
export class Test<IEntityData extends ITestData = ITestData>
extends Entity<IEntityData> {
constructor(testData: ITestData) {
super(testData);
}
get foo(): string { return this.source.foo }
get bar(): number { return this.source.bar }
}
Во время сборки у меня возникает ошибка. Я не могу понять, что я делаю не так.
src/app/data/models/test.ts:13:11 - error TS2345: Argument of type 'ITestData' is not assignable to parameter of type 'IEntityData'.
'ITestData' is assignable to the constraint of type 'IEntityData', but 'IEntityData' could be instantiated with a different subtype of constraint 'ITestData'.
13 super(testData);
Ответ №1:
О боже! Решено! Я просто заменил это:
constructor(testData: ITestData) {
super(testData);
}
с этим:
constructor(testData: IEntityData) {
super(testData);
}