简体   繁体   English

pipe 错误:类型“数字”不可分配给类型“字符串”

[英]pipe error : Type 'number' is not assignable to type 'string'

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'concat',
  pure: true,
})
export class ConcatPipe implements PipeTransform {
  public transform(value: string, args: string[]): string {
    return value?.concat(...args);
  }
}

When I try to concating in ngFor:当我尝试在 ngFor 中连接时:

 <mat-option *ngFor="let name of names$ | async; index as i" [value]="i" [id]="'firstName' | concat: [i]">

I have this pipe where I concat things in the template side, but i get this error:我有这个 pipe 我在模板端连接东西,但我得到这个错误:

Type 'number' is not assignable to type 'string'

How can I fix or extend my pipe?如何修复或扩展我的 pipe?

It means you receive numbers, not strings.这意味着您收到的是数字,而不是字符串。 You should first try to log what happens in value and args .您应该首先尝试记录valueargs中发生的情况。 Then you would have to cast numbers into string:然后你必须将数字转换成字符串:

let strValue: string;
if (typeof value === 'number') {
  strValue = parseInt(value);
} else {
  strValue = value;
}

same goes for the args array: args 数组也是如此:

argsStrs: string[] = args.map(arg => {
  if (typeof arg === 'number') {
    return parseInt(arg);
  } else {
    return arg;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误:使用 toFixed() 无法将类型“字符串”分配给类型“数字” - Error: Type 'string' is not assignable to type 'number' with toFixed() 类型&#39;字符&#39;不能指定为&#39;数字&#39;类型 - Type 'string' is not assignable to type 'number' “数字”类型不能分配给“字符串”类型 - Type 'number' is not assignable to type 'string' 类型字符串不可分配给类型编号 - Type string is not assignable to type number 错误 TS2322:“数字”类型不可分配给“字符串”类型 - error TS2322: Type 'number' is not assignable to type 'string' 错误 TS2322:键入“字符串 | null' 不可分配给类型 'number' - error TS2322: Type 'string | null' is not assignable to type 'number' 错误 TS2322:类型“数字”不可分配给 angular 中的类型“字符串” - error TS2322: Type 'number' is not assignable to type 'string' in angular 如何解决 Angular 14 中的错误“类型'字符串'不可分配给类型'数字'”? - How to solve error "Type 'string' is not assignable to type 'number'" in Angular 14? 类型为&#39;number&#39;的参数不能赋值给&#39;string&#39;类型的参数 - argument of type 'number' is not assignable to a parameter of type 'string' “字符串”类型的参数不能分配给“数字”类型的参数 - Argument of type 'string' is not assignable to parameter of type 'number'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM