首页 > 解决方案 > html:21:40 - 错误 TS2362:算术运算的左侧必须是“any”、“number”、“bigint”类型或枚举类型

问题描述

HTML

<star-rating
  value="{{(res.popularity| number : '1.0-0') /20 }}"
  totalstars="{{totalstar}}"
  checkedcolor="yellow"
  uncheckedcolor="black"
  size="24px"
  readonly="true"
  (rate)="onRate($event)"
></star-rating>

如图所示,我有很多问题。有人可以解释一下这个问题吗

在此处输入图像描述

标签: angulartslintangular10

解决方案


正如迈克尔 D 在上面的评论中所说, DecimalPipe (又名 | 数字)将数字转换为字符串,因此您无法将其进一步传递给数字类型的 @Input() 。

您可以为您的项目以一种干净且可重用的方式修复它,即创建一个自定义管道,该管道接受一个表示小数的字符串并将其转换为“数字”类型。就是这样:

as-number.pipe.ts

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

@Pipe({
    name: 'asNumber',
    pure: false
})
export class AsNumberPipe implements PipeTransform {
    transform(value: string): unknown {
        return parseFloat(value);
    }
}

不要忘记在app.module.ts文件中声明它(或您将要使用它的功能模块):

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AsNumberPipe } from './pipes/as-number.pipe';

@NgModule({
  declarations: [
    AppComponent,

    AsNumberPipe
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

现在你可以像这样在你的 html 模板中使用它:

<star-rating
  value="{{(res.popularity | number : '1.0-0' | asNumber) / 20 }}"
  totalstars="{{totalstar}}"
  checkedcolor="yellow"
  uncheckedcolor="black"
  size="24px"
  readonly="true"
  (rate)="onRate($event)"
></star-rating>

奖金:

根据我在您的错误转储中看到的内容,您还有一些与 StarRating 组件的其他两个输入绑定相关的错误。

  1. totalstars="{{totalstar}}"//错误:类型“字符串”不可分配给类型“数字”。

要解决此问题,您可以使用我们在上面创建的相同管道,如下所示:

totalstars="{{totalstar | asNumber}}"
  1. readonly="true" // 错误:类型 'string' 不可分配给类型 'boolean'。

为此,您只需要通过用尖括号包装属性来确保您确实将“true”作为布尔值传递:

[readonly]="true"

所以最后你的html标签看起来像这样:

<star-rating
  value="{{(res.popularity | number : '1.0-0' | asNumber) / 20 }}"
  totalstars="{{totalstar | asNumber}}"
  checkedcolor="yellow"
  uncheckedcolor="black"
  size="24px"
  [readonly]="true"
  (rate)="onRate($event)"
></star-rating>

推荐阅读