#Is it possible to derive types from a json file?

5 messages · Page 1 of 1 (latest)

violet haven
#

I have a static json file that contains objects that look like this:

"properties": [ 
{
   "name": "MyPrettyProperty",
   "dataType": "PropertyLongString",
    ...
},
{
   "name": "MyCoolBoolProp",
   "dataType": "PropertyBoolean",
    ...
}]```
The json is more complex than that, but that's the part I'm interested in.

Is it possible to import this json, and derive from it a type that would look like this:
```ts 
{
   MyPrettyProperty: string;
   MyCoolBoolProp: boolean;
}```

Perhaps it's not possible since importing the json would mean knowing about its contents at runtime?
broken verge
#

does the file have to be a JSON file? or could it be a .ts file with contents like:

export default {
    "properties": [ 
    {
       "name": "MyPrettyProperty",
       "dataType": "PropertyLongString",
        ...
    },
    {
       "name": "MyCoolBoolProp",
       "dataType": "PropertyBoolean",
        ...
    }]
} as const
violet haven
#

the file comes from a 3rd party api so I cannot change it. I created a small node app that parses the json file and outputs a d.ts with my own transformations, so that works I guess. I'm still curious if my question is technically possible or not. I'm leaning towards no, because when you set "resolveJsonModule": true in tsconfig all the imports of json files seem to automatically do some kind of type conversion (converting all the values to primitives). In my use case I actually need the values to be static when imported as to have any chance to do some typescript type juggling.

broken verge
violet haven