输入'字符串| string[]' 不能分配给类型 'string' - 打字稿类型错误

时间:2021-04-14 09:14:29

标签: angular typescript

我正在尝试使用 Accordion 库中的 Ng-Lightning 组件。

我的 html:

<ul ngl-accordion [(activeName)]="active">
  <ng-template nglAccordionSection name="B" label="Accordion Title A">This is the content area for section A
  </ng-template>
</ul>

<div class="slds-m-top_large">Active Section Name: <b>{{ active | json }}</b></div>

和我的组件文件:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-list-item',
  templateUrl: './list-item.component.html',
  styleUrls: ['./list-item.component.scss']
})
export class SuggestedReferenceListItemComponent implements OnInit {

  active='B';

  constructor() { }
  ngOnInit(): void {}

}

我在尝试编译代码时看到以下警告:

Error: src/app/list-item/list-item.component.html:3:35 - error TS2322: Type 'string | string[]' is not assignable to type 'string'.
Type 'string[]' is not assignable to type 'string'.

<ul ngl-accordion [(activeName)]="active">

谁能告诉我为什么我会看到该警告以及如何解决它?

1 个答案:

答案 0 :(得分:1)

在 Ng-Lightning 中,activeName 在这里定义:

enter image description here

并且您的组件 active='B'; 仅像字符串一样定义。

所以,你可以试试:

active: string | string[] = 'B';

或者如果它真的不起作用

active: any = 'B';