Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: cannot cast value from json to [number, number] tuple

I'm pretty new to TypeScript. Maybe my question is obvious, but I can't find any solution.

I have a config.json file like this:

{
  "api": {
    "baseUrl": "http://localhost:9000/api",
    "list": {
      "itemsPerPage": 200
    }
  },
  "map": {
    "start": {
      "position": [51.505, -0.09],
      "zoom": 2
    },
    "leaflet": {
      "minOpacity": 0.3,
      "accessToken": "something"
    }
  }
}

I import it into some module.tsx

import config from '../config.json';
const mapCenter: [number, number] = config.map.start.position;

position from json need to be treated as [number, number] tuple, because some library that I use requires it to be typed like this. But unfortunately I get an error:

TS2322: Type 'number[]' is not assignable to type '[number, number]'. Property '0' is missing in type 'number[]'.

How to cast types correctly?

Can I declare type of my json using config.d.ts file? How?

Thank you in advance.

like image 368
pxx Avatar asked Nov 07 '22 03:11

pxx


1 Answers

Since Tuples in typescript are glorified arrays, you can use the "as" keyword to cast it to your type:

const mapCenter: [number, number] = config.map.start.position as [number, number];
like image 136
bug-a-lot Avatar answered Nov 14 '22 22:11

bug-a-lot