1

I am making an API call with Axios which returns JSON. The API returns CUSIP as type String, however, I would like to receive it as type Number. I created an interface which has the typescript type as number however when I get the variable, it is still treated as a String.

API Call and some logic:

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);

        });

    }
}

interface called General where I cast CUSIP to number:

export interface General {
    ISIN: string;
    CUSIP: number;
}

The problem: instead of printing [CUSIP + 1337] as [2 + 1337 = 1339], it is printing [21337]. Would love some help thanks. I really dont want to have to cast everything manually in a constructor.

  • `let num = Number(gen.CUSIP) + 1337`? – Juan Mendes Aug 27 '19 at 14:25
  • 1
    Not sure what "I really dont want to have to cast everything manually in a constructor." means. You have no constructors... Also, casting in TypeScript never changes the variable, it's just telling the compiler that you know what you are doing, which in this case, you didn't because the underlying object is still a string :p – Juan Mendes Aug 27 '19 at 14:30

2 Answers2

0

Try changing CUSIP from a string to a number:

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);
      });
  }
};

Peter
  • 2,041
  • 1
  • 12
  • 25
0

You have to remember that Typescript is only a layer of types above Javascript, it will not modify the actual javascript.

In your case, even if CUSIP is typed as a number, the actual data you received is a string. You should declare what you get from the API as a string and then cast it as a number with parseInt(gen.CUSIP, 10).

Axnyff
  • 7,275
  • 2
  • 26
  • 31