在创建对象时,Typescript将数字自动转换为字符串

问题描述 投票:0回答:2

我有一个通用的函数,它接受字段(类属性)并从中创建一个POST请求。

代码是这样的:

public state: number;

updateField(field: string | number, name: string, team: boolean = true) {
  this.http.post('/update_key', {
        [path]: { [name]: field }
  })
}

在这里,path是一个变量,具有像/ipl_data/match_info/current_match这样的火力基础路径

我称之为this.updateField(this.state, 'state', false);

发送此请求时,请求正文创建如下:

{
  "/ipl_data/match_info/current_match": {
    "state":"3"
  }          ^------ this should be a number since type was defined as number
}

有办法解决这种情况吗?

angular typescript http http-post
2个回答
0
投票

首先是你的this.state === "3"。检查this.state被分配值的地方。

这更像是一个“javascript”问题而不是“打字稿”问题。您需要了解typescript对代码的运行时行为没有任何影响,它只适用于您的IDE以及编译代码时。


0
投票

我会尝试类似的东西:

updateField(field: string | number, name: string, team: boolean = true) {
  this.http.post('/update_key', {
        [path]: { [name]: !isNaN(field) ? +field : field }
  })
}
© www.soinside.com 2019 - 2024. All rights reserved.