skip to Main Content

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


  1. This should work. Playground

      const json = { "a": { "b": "1" }, "c": {"d": "1"} }; // <-- simulate import
    
      type Unsafe = { [parentKey: string]: {[childKey: string]: any} } ;
      // key not tpyed
      let k = "a"
    
      const t: Unsafe = json;
      console.log(t["a"]); 
      console.log(t[k]);   // <- ok but could fail on runtime
    
      // safe approch
      type Safe =Record<'a'| 'c', {[key: string]: string}>
      // typed key
      let saveKey: keyof Safe = "a"          // <- variable key
      
      const safe: Safe  = json;
      console.log(safe['a'])
      console.log(safe[saveKey])
      
    
    Login or Signup to reply.
  2. This might be working

    const t = {
        "a": {
            "b": "1"
        }
    }
    type JsonKeys = keyof typeof t;
    let k: JsonKeys = "a"; // <- variable key
    
    console.log(t["a"]); // <- ok
    console.log(t[k]);   // <- ok 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search