简体   繁体   中英

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

I really did not understand how the type assignment system works for variables in typescript. Can anyone help me why this does not work. Thank you

valorParcela:number;
totalCost:number;
VendaProdutoVendaNParcelas: number;

this.valorParcela = Number( this.totalCost / this.VendaProdutoVendaNParcelas).toFixed(2);

I expected a simple parseFloat

toFixed returns a string which you are assigning to a variable which should be number . You need another pair of () to convert the result of toFixed back to number

this.valorParcela = Number(( this.totalCost / this.VendaProdutoVendaNParcelas).toFixed(2));

Or you can use the unary + trick to perform number conversion:

this.valorParcela = +(this.totalCost / this.VendaProdutoVendaNParcelas).toFixed(2);

toFixed() returns string. throwing an error because trying to assign to the number type. so just cast to Number(expression) again or make this variable as string this.valorParcela

this.valorParcela = Number(Number(this.totalCost / this.VendaProdutoVendaNParcelas).toFixed(2)));
.toFixed(2);

Always returns string.

And you have assigned type number .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM