Currently, I am facing an issue while attempting to import a JSON file that contains keys with unknown values (such as device names) in TypeScript. I am struggling to access the imported data with variable keys at runtime.
For example, consider the following JSON file named "test.json":
{
"a": {
"b": "1"
}
}
Here is a snippet of TypeScript code for reference:
import t from "./test.json";
let k = "a" // <- variable key
console.log(t["a"]); // <- ok
console.log(t[k]); // <- error
The TypeScript error message displayed is as follows: The element implicitly possesses an 'any' type because the expression of type 'string' cannot 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 have done some research on TypeScript Records and Index Signatures, but I am unsure how to effectively import or "cast" the JSON data so that it can be accessed using variable keys. It is important that the data is validated at runtime.