如何解决Angular 14中‘Type 'string' is not assignable to type 'number'’错误?
解决Angular 14中
Type 'string' is not assignable to type 'number'类型错误 问题根源很明确:你在模板里给<app-total>的total属性传的是字符串"5000",但组件里定义的total是number类型,Angular模板中直接写的属性值默认会被解析为字符串,所以触发了类型不匹配错误。
给你两种解决方式:
方式一:使用属性绑定语法(推荐)
把total属性用方括号包裹,Angular会把里面的值当作JavaScript表达式解析,直接识别为数字:
<div> <app-header></app-header> <app-total mensaje="Total por pagar: " [total]="5000"></app-total> <app-items></app-items> </div>
方式二:在组件内做类型转换
如果需要兼容字符串形式的输入,可以在组件里通过setter自动转换类型:
import { Component, Input, OnInit } from '@angular/core'; @Component({ selector: 'app-total', templateUrl: './total.component.html', styleUrls: ['./total.component.css'] }) export class TotalComponent implements OnInit { private _total: number = 0; @Input() set total(value: string | number) { // 把字符串转成数字,非字符串直接赋值 this._total = typeof value === 'string' ? Number(value) : value; } get total(): number { return this._total; } @Input() mensaje:string = ''; constructor() { } ngOnInit(): void { } }
这种方式下,不管模板里传的是字符串还是数字,组件内部都会处理成number类型。
内容的提问来源于stack exchange,提问作者Felipe Antonio Guzmán Anabalon
相关产品推荐
相关产品推荐

