【发布时间】:2019-12-31 18:11:24
【问题描述】:
我正在使用返回 JSON 的 Axios 进行 API 调用。 API 将 CUSIP 作为 String 类型返回,但是,我希望将其作为 Number 类型接收。我创建了一个 typescript 类型为 number 的接口,但是当我获取变量时,它仍然被视为 String。
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);
});
}
}
我将 CUSIP 转换为数字的名为 General 的接口:
export interface General {
ISIN: string;
CUSIP: number;
}
问题:不是将 [CUSIP + 1337] 打印为 [2 + 1337 = 1339],而是打印 [21337]。希望得到一些帮助谢谢。我真的不想在构造函数中手动转换所有内容。
【问题讨论】:
-
let num = Number(gen.CUSIP) + 1337? -
不确定是什么“我真的不想在构造函数中手动转换所有内容。”方法。您没有构造函数...此外,TypeScript 中的强制转换永远不会更改变量,它只是告诉编译器您知道自己在做什么,在这种情况下,您不知道,因为底层对象仍然是一个字符串:p
标签: javascript typescript axios