我有一个通用的函数,它接受字段(类属性)并从中创建一个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
}
有办法解决这种情况吗?
首先是你的this.state === "3"
。检查this.state
被分配值的地方。
这更像是一个“javascript”问题而不是“打字稿”问题。您需要了解typescript对代码的运行时行为没有任何影响,它只适用于您的IDE以及编译代码时。
我会尝试类似的东西:
updateField(field: string | number, name: string, team: boolean = true) {
this.http.post('/update_key', {
[path]: { [name]: !isNaN(field) ? +field : field }
})
}