我正在使用Axios进行API调用,它返回JSON。API以类型字符串的形式返回CUSIP,但是,我希望以类型编号的形式接收它。我创建了一个接口,它的typescript类型为number,但是当我获得变量时,它仍然被视为字符串。
API调用和一些逻辑:
const axios = require('axios');
import { General } from './json-objects-new';
module.exports = {
makeApiCall : function(ticker:string) {
axios.get(`${API_ENDPOINT}${ticker}?api_token=${API_KEY}`)
.then(function (response) {
// handle success
return response.data;
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(data => {
let gen : General = data.General;
let num = gen.CUSIP + 1337
console.log(num);
});
}
}
接口名为General,其中我将CUSIP转换为number:
export interface General {
ISIN: string;
CUSIP: number;
}
问题:不是将CUSIP + 1337打印为2+ 1337 = 1339,而是打印21337。希望能帮上忙谢谢。我真的不想在构造函数中手动强制转换所有内容。
发布于 2019-08-27 14:26:08
尝试将CUSIP
从字符串更改为数字:
const axios = require("axios");
import { General } from "./json-objects-new";
module.exports = {
makeApiCall: function(ticker: string) {
axios
.get(`${API_ENDPOINT}${ticker}?api_token=${API_KEY}`)
.then(function(response) {
// handle success
return response.data;
})
.catch(function(error) {
// handle error
console.log(error);
})
.then(data => {
let gen: General = data.General;
let num = Number(gen.CUSIP) + 1337; /* convert CUSIP string to number */
console.log(num);
});
}
};
发布于 2019-08-27 14:26:55
您必须记住,Typescript只是Javascript之上的一层类型,它不会修改实际的javascript。
在您的示例中,即使CUSIP被键入为数字,您收到的实际数据也是一个字符串。您应该将从API获得的内容声明为字符串,然后使用parseInt(gen.CUSIP, 10)
将其转换为数字。
https://stackoverflow.com/questions/57676760
复制相似问题