Typescript:尝试添加两个变量,但得到两个变量的连接

Typescript : Trying the addition of two variables but get the concatenation of the two

本文关键字:两个 变量 连接 Typescript 添加      更新时间:2023-09-26

我的Typescript类中有三个变量:

A:number;
B:number;
C:number;

在类的另一部分中,我尝试添加两个变量A和B:

this.C = this.A+this.B; // A =20 and B = 50;
在html模板 中显示C
<span>{{C}}</span>

我的问题是,而不是得到两个变量(20+50=70)的添加,我得到连接(2050)!!

有人能帮帮我吗?

UPDATE:

下面是导致问题的代码部分:

goTo(page:number,type:script) {
    //    
    this.pageFirstLineNumber = page;
    this.pageLastLineNumber = page + this.LINE_OFFSET; //concatenation!!
}

注意pageLastNumber被声明为数字类型,LINE_OFFSET也是数字类型,我已经找到了解决这个问题的方法,但是typescript编译器输出一个错误(禁止eval):

////
....
this.pageFirstLineNumber = eval(page.toString()); // now It works !!
this.pageLastLineNumber = page + this.LINE_OFFSET; //concatenation!!

下面是LINE_OFFSET变量的声明:
private _calculateOffset(fontSize: number) {
    let linesDiff = (fontSize * 27) / 14;
    let lines:number = 27 - (linesDiff - 27);
    this.LINE_OFFSET = Math.floor(lines);
    if (fontSize >= 17 && fontSize <= 20) {
        this.LINE_OFFSET += (Math.floor(fontSize / 3) - 2);
    }
    if (fontSize > 20 && fontSize <= 23) {
        this.LINE_OFFSET += (Math.floor(fontSize / 2) - 2);
    }
    if (fontSize > 23 && fontSize <= 25) {
        this.LINE_OFFSET += (Math.floor(fontSize / 2));}
    if (fontSize > 25 && fontSize <= 27) {
        this.LINE_OFFSET += (Math.floor(fontSize / 2) + 1);
    }
    if (fontSize > 27 && fontSize <= 30) {
        this.LINE_OFFSET += (Math.floor(fontSize / 2) + 4);
    }
}

在数字前加上+:

let a = +b + +c;

ref

当你在一个接口中声明一个属性是number,那么它只会作为一个声明,它不会被翻译成javascript。

例如:

interface Response {
    a: number;
    b: number;
}
let jsonString = '{"a":"1","b":"2"}';
let response1 = JSON.parse(jsonString) as Response;
console.log(typeof response1.a); // string 
console.log(typeof response1.b); // string
console.log(response1.a + response1.b); // 12

正如你所看到的,json有ab作为字符串,而不是作为数字,并且在接口中将它们声明为数字对运行时结果没有影响。

如果你从你的服务器得到的编码为字符串而不是数字,那么你需要转换它们,例如:

let response2 = {
    a: Number(response1.a),
    b: Number(response1.b)
} as Response;
console.log(typeof response2.a); // number 
console.log(typeof response2.b); // number
console.log(response2.a + response2.b); // 3

(playground中的全部代码)

问题是变量类型转换没有完成。你需要按下列方法去做。

A: parseInt(number);B: parseInt(number);

那么你将得到sum C= A+b而不是串联

我遇到了类似的问题,能够解决如下:

C:number =0;
A:number=12;
B:number=0.4;
C= Number.parseInt(A.toString()) + Number.parseFloat(B.toString());
console.log("C=" + C );

似乎很愚蠢,将数字转换为字符串并再次解析为数字,但这就是我解决问题的方法。

最后我找到了导致错误的原因,我从html模板中得到了page变量(它是一个输入值),它在函数参数中被定义为数字类型,但实际上是一个字符串,typescript不能从html模板中检查变量的类型,所以当一个尝试parseInt(page)静态类型突出显示错误!我通过给页面变量一个"类型来解决这个问题,然后对页面变量应用parseInt。

这意味着在A或B变量中存在字符串值。检查代码中的不安全部分,我的意思是将服务器响应转换为<any>,并将服务器响应转换为接口。这可能导致number变量中有string值。

const value = Number(stringOrNum)+1;