【问题标题】:Cast String to Number in Typescript on JSON API response in Typescript [duplicate]在 Typescript 中的 JSON API 响应中将 String 转换为 Number [重复]
【发布时间】: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


【解决方案1】:

你要记住,Typescript 只是 Javascript 之上的一层类型,它不会修改实际的 javascript。

在您的情况下,即使 CUSIP 输入为数字,您收到的实际数据也是一个字符串。您应该将从 API 获得的内容声明为字符串,然后使用 parseInt(gen.CUSIP, 10) 将其转换为数字。

【讨论】:

    【解决方案2】:

    尝试将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);
          });
      }
    };
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-15
      • 2019-08-06
      • 2017-12-01
      • 2018-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多