When working with typescript 3.0.3, I encountered an issue while importing a json file in the following manner:
import postalCodes from '../PostalCodes.json';
The json file has the structure shown below:
{
"555": { "code": 555, "city": "Scanning", "isPoBox": true },
"800": { "code": 800, "city": "Høje Taastrup", "isPoBox": true },
"877": { "code": 877, "city": "København C", "isPoBox": true },
"892": { "code": 892, "city": "Sjælland USF P", "isPoBox": true },
"893": { "code": 893, "city": "Sjælland USF B", "isPoBox": true },
"897": { "code": 897, "city": "eBrevsprækken", "isPoBox": true },
"899": { "code": 899, "city": "Kommuneservice", "isPoBox": true },
"900": { "code": 900, "city": "København C", "isPoBox": true },
"910": { "code": 910, "city": "København C", "isPoBox": true },
"917": { "code": 917, "city": "Københavns Pakkecenter", "isPoBox": true },
... and so on
The goal is to utilize it as demonstrated below:
// first.postalCode is of type string
const x = postalCodes[first.postalCode];
However, this results in the error: "Element implicitly has an 'any' type because type '...very long type signature...' has no index signature."
Is there a method to make this function properly using the automatically generated json types, allowing for dynamic lookup of a postal code based on its string key?
Currently, my workaround involves creating an intermediary ts file like:
import postalCodes from './PostalCodes.json';
export const PostalCodesLookup = postalCodes as {
[key: string]: { code: number, city: string, isPoBox: boolean }
};