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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With