I’m trying to import a JSON file with arbitrary keys (e. g. device names) but can’t figure out how to access the imported data with variable (unknown) keys at runtime in TypeScript.
Example JSON file "test.json":
{
"a": {
"b": "1"
}
}
Example TS code:
import t from "./test.json";
let k = "a" // <- variable key
console.log(t["a"]); // <- ok
console.log(t[k]); // <- error
The TypeScript error:
Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘{ a: { b: string; }; }’.
No index signature with a parameter of type ‘string’ was found on type ‘{ a: { b: string; }; }’.
I’ve already read about TypeScript Records and Index Signatures, but how would I import or "cast" the imported JSON data so that it can be accessed using variable keys? The data will (must) be verified at runtime.
2
Answers
This should work. Playground
This might be working