Home > Software engineering >  Creating a type based on a JSON file's keys
Creating a type based on a JSON file's keys

Time:01-06

Is it possible to create a type from an imported json module's content?

i.e.

import * as config from './config.json'

config.json

{
    "known_value": {
        "unknown_key": "value",
        "unknown_key2": "value2",
    }
}

I tried

type functions = keyof config.known_value;

hoping to produce:

type functions = 'unknown_key' | 'unknown_key2';

CodePudding user response:

Edit

I actually misread the question, you didn't simply miss one step, you were missing the typeof concept, which can be used to extract the type from a value.


You are simply missing the last step, to extract the keys of known_value

type Keys = keyof typeof config.known_value
  •  Tags:  
  • Related