角开关盒类型检查的正确类型是什么?

时间:2021-05-18 22:13:03

标签: angular typescript

我有以下类型和接口:

interface TypeA {
  type: 'a';
  foo: 'foo';
  ...
}

interface TypeB {
  type: 'b';
  bar: 'bar';
  ...
}

interface TypeC {
  type: 'c';
  baz: 'baz';
  ...
}

type Row = Column[];

type Column<T = TypeA | TypeB | TypeC> = T;

在我的模板文件中,我有以下 html 代码:

<div *ngFor="let column of row">
  <ng-container [ngSwitch]="column.type">
    <type-a-component
      *ngSwitchCase="'a'" 
      [data]="column"
    ></type-a-component>

    <type-b-component 
      *ngSwitchCase="'b'" 
      [data]="column"
    ></type-b-component>

    <type-c-component 
      *ngSwitchCase="'c'" 
      [data]="column"
    ></type-c-component>
  </ng-container>
</div>

组件输入有以下类型:

// type-a-component.ts
@Component()
export class TypeAComponent {
  @Input()
  data: Column<TypeA>;
}

// type-b-component.ts
@Component()
export class TypeBComponent {
  @Input()
  data: Column<TypeB>;
}

// type-c-component.ts
@Component()
export class TypeCComponent {
  @Input()
  data: Column<TypeC>;
}

我在模板类型检查中遇到以下错误:

Type 'TypeA | TypeB | TypeC' is not assignable to type 'TypeA'.
Type 'TypeA | TypeB | TypeC' is not assignable to type 'TypeB'.
Type 'TypeA | TypeB | TypeC' is not assignable to type 'TypeC'.

我是否写错了类型定义,或者在这里可以做什么?

0 个答案:

没有答案