如果我在
array: (A | B)[]
中使用 *ngFor
似乎选项是在整个模板上使用 $any()
。
有没有办法正确地做到这一点?
我完全避免使用
$any()
打字,但感觉很糟糕。我在模板中看到的有关类型联合的所有其他帖子都是特定的实现,总体感觉很hacky。
编写一个定义类型的方法,该方法将在 ngFor 中使用!
get arrayA(): A {
return this.array as A;
}
get arrayB(): B {
return this.array as B;
}
我想你可以定义
export type typeAB=A & B
arrayAB=this.array as typeAB
并循环数组AB
<div *ngFor="let element of arrayAB">{{element}}</div>
例如使用按钮
toogleChange()
{
if (this.arrayAB==this.array2 as typeAB[])
this.arrayAB=this.array as typeAB[]
else
this.arrayAB=this.array2 as typeAB[]
}