根据@Input装饰器更改属性类型

时间:2020-07-29 12:14:49

标签: javascript angular typescript typescript-typings

取决于是否已设置@Input装饰器,TypeScript中是否可以有冲突类型?

我有一个简单的选择组件。它提供单个或多个选择。可以通过将multiple @Input设置为true来定义多项选择。

@Component({...})
export class SelectComponent {
  // The type for 'selectedValue' should be conditional
  public selectedValue: string | string[];
  @Input() public multiple = false;
}

然后,我在模板中使用组件,并在组件中引用它。在这种情况下,不使用multiple输入就使用选择。

<my-select #selectRef><my-select>
@Component({...})
export class AppComponent {
  // ...
  // In this case TypeScript should know that the 'multiple' input was not set on the
  // <my-select> component, therefore the 'selectedValue' should be of 'string' type.

  doSingleValueOperation(this.selectRef.selectedValue);
}

在这种情况下,设置了multiple输入。

<my-select #selectRef [multiple]="true"><my-select>
@Component({...})
export class AppComponent {
  // ...
  // In this case 'multiple' attribute is set, therefore the type should be 'string[]'.
  doMultipleValuesOperation(this.selectRef.selectedValue);
}

0 个答案:

没有答案