为了更好的封装,我想创建一个包含多种其他类型的新类型。 entityService
应键入为 OakService
或 MapleService
,并应包含在 TreeService
内。
您可以在评论中看到一种可能的解决方案。如果我取消注释 garden.component.ts 中的导入并将 TreeService
替换为 OakService | MapleService
,它会起作用,但我想要某种父类型,其中包括所有这些。
tree.service.ts
import { OakService } from './oak.service';
import { MapleService } from './maple.service';
export type TreeService = typeof OakService | MapleService;
oak.service.ts
import { BaseService } from './base.service';
@Injectable()
export class OakService extends BaseService {
constructor() {
super();
}
}
maple.service.ts
import { BaseService } from './base.service';
@Injectable()
export class MapleService extends BaseService {
constructor() {
super();
}
}
garden.component.ts
// import { OakService } from './oak.service';
// import { MapleService } from './maple.service';
import { TreeService } from './parent.service';
@Component()
export class GardenComponent {
constructor(
protected entityService: TreeService // OakService | MapleService
) {}
}
balcony.component.ts
import { MapleService } from './maple.service';
export class BalconyComponent extends GardenComponent {
constructor(
protected mapleService: MapleService
) {
super(mapleService);
}
}
Info: The code above does not work. Your have to use the code inside the comments. The error I've got is not inside balcony.component.ts: ERROR in : Can't resolve all parameters for BaseListComponent in .../garden.component.ts: (?).
最佳答案
可注入(inject)类中的参数类型允许跳过 TypeScript 中的 Angular @Inject
装饰器,并注释用于依赖注入(inject)的构造函数。类型在运行时不存在并且无法注入(inject)。
GardenComponent
无法成为可用组件。由于用作抽象类,因此它不应该具有 @Component
装饰器:
export abstract class GardenComponent {
constructor(
protected entityService: TreeService // OakService | MapleService
) {}
}
虽然子类应该有@Component
:
@Component(...)
export class BalconyComponent extends GardenComponent {
constructor(mapleService: MapleService) {
super(mapleService);
}
}
构造函数在子类中是必需的,因为父类不包含正确的注释,并且它们的参数不应该具有可见性修饰符,因为 this.entityService
已由父构造函数分配。
关于javascript - 如何导出多个类型别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49277439/