错误 TS2322:输入“字符串 |” string[]' 不可分配给类型 'string'

问题描述 投票:0回答:1

我有一个数据类型为字符串的 @Input() 属性 | string[],在升级到 Angular 16 之前它工作正常,但是在升级到 Angular 16 之后我一直收到此错误。 我不知道我哪里错了。

 @Input() info: string | string[];

我不确定出了什么问题。

我已经尝试过制作如下所示的类型。

export type stringOrArray = string | string[];

但遇到了同样的错误。

angular typescript angular16
1个回答
1
投票

由于有两种可能的类型

string
string[]
,我们需要明确告诉打字稿您要分配的值属于哪种类型

this.test = <string>this.info;

完整代码:

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

@Component({
  selector: 'app-child',
  standalone: true,
  imports: [],
  templateUrl: './child.component.html',
  styleUrl: './child.component.css',
})
export class ChildComponent {
  @Input() info!: string | string[];
  test: string = '';
  ngOnInit() {
    if(typeof this.info === 'string') {
        this.test = this.info;
    }
  }
}

Stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.