TS2322子类中缺少属性,但它就在那里

时间:2017-05-04 20:53:06

标签: angular typescript

我有两个Angular 4组件类。

超类:

export class SectionComponent implements OnInit {
  slides: SlideComponent[];

  constructor() {
  }

  ngOnInit() {
  }

}

子类:

export class FrontPageSectionComponent extends SectionComponent implements OnInit {
  slides: SlideComponent[];

  constructor() {
    super();
  }

  ngOnInit() {
    this.slides = [];
  }

}

我尝试在AppComponent中创建一个超类数组...

export class AppComponent implements OnInit {
  sections: SectionComponent[];

  constructor() {
  }

  ngOnInit(): void {
    this.sections = [
      FrontPageSectionComponent
    ];
  }
}

但是我收到了一个错误:

  

TS2322:类型'typeof FrontPageSectionComponent []'不能分配给'SectionComponent []'类型。类型'typeof FrontPageSectionComponent'不能分配给'SectionComponent'类型。 “typeof FrontPageSectionComponent”类型中缺少属性“幻灯片”。

我自己没有指定任何类型,并且在代码库中搜索'typeof FrontPageSectionComponent'不会产生任何结果,所以我假设这是TypeScript推理。

2 个答案:

答案 0 :(得分:1)

你的数组

Stream.of(p1,p2,p3,p4).collect(groupingBy(Person::getState, mapping(d -> d.getSalary(), toList())))
.forEach((state,wageList) -> {
        System.out.print(state+"-> ");
        final BigDecimal[] wagesArray = wageList.stream()
                .map(bd -> new BigDecimal[]{bd, BigDecimal.ONE})
                .reduce((a, b) -> new BigDecimal[]{a[0].add(b[0]), a[1].add(BigDecimal.ONE)})
                .get();
        System.out.println(wagesArray[0].divide(wagesArray[1])
                                        .setScale(2, RoundingMode.CEILING));
    });

声明一组sections: SectionComponent[]; 个实例。

如果你想声明一个派生自SectionComponent的类数组,你实际上可以。

您需要使用类的类型,而不是其实例的类型。

要获取值的类型,请使用SectionComponent关键字。

typeof

因此,要声明构造const c: typeof SectionComponent = SectionComponent; 实例的类数组,您将编写。

SectionComponent

更抽象地说,你可以写

sections: Array<typeof SectionComponent>;

这种技术在高阶编程中非常有用。

注意我在嵌套时纯粹使用sections: Array<new () => SectionComponent>; 语法,Array<...>也可以

答案 1 :(得分:0)

当我而不是FrontPageComponentnew FrontPageComponent()插入数组时,它就可以了。

然后我想起了Angular知道如何构建这些内容,现在我这样做了:

export class AppComponent implements OnInit {
  sections: SectionComponent[];

  constructor(private frontPage: FrontPageSectionComponent) {
  }

  ngOnInit(): void {
    this.sections = [
      this.frontPage,
    ];
  }
}

错误消失了。如果这仍然是错误的做法,请告诉我。

我实际上是将这些部分移动到一个SectionService来分离关注点(构造函数会快速填满),但是因为当我用Google搜索时我没有找到任何好的结果,所以我把它放了。

相关问题