1

Say I have this JSON file:

{
  "foo": 1,
  "bar": true,
  "baz": "yes"
}

is there a way to import that file and get static typing with TypeScript?

with plain Node.js, we do:

const json = require('./file.json');

but with TS, is there a way to do:

import json = require('./file.json');

is there not a way to get static typing like this? It should be easy, right?

IMO, you should just be able to do

typeof 'path/to/json/file.json'

so that would be:

export type MyInterface = typeof 'path/to/json/file.json'

and that will give you a type.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • Why not just create an interface, and then assert the type once you get the request response? https://stackoverflow.com/questions/22875636/how-do-i-cast-a-json-object-to-a-typescript-class?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – diopside May 04 '18 at 19:07
  • 1
    Using an interface is just inconvenient, your interface constantly has to be up-to-date with the JSON, and vice versa. – Alexander Mills May 04 '18 at 19:13
  • True... so your edit is suggesting there should be some built-in method for like, generating interfaces on an ad-hoc basis? Not a bad idea – diopside May 04 '18 at 19:15
  • 1
    Well you wouldn't need to generate the interface. TS interfaces are static, so is JSON. Why not be able to use the JSON itself as the interface. It has a name - the filepath to the JSON file is the name. – Alexander Mills May 04 '18 at 19:16
  • 1
    I escalated this to a feature request, since I don't expect to get the answer I am looking for: https://github.com/Microsoft/TypeScript/issues/23895 – Alexander Mills May 04 '18 at 19:21
  • Seems like a great idea for local JSON files. – diopside May 04 '18 at 19:24

1 Answers1

2

You can essentially do the same as standard Node.js but use an interface and attach it to the variable you're require-ing into.

interface File {
  foo: number
  bar: boolean
  baz: string
}

const jsonFile: File = require('./file.json')

If the data read and parsed from the file doesn't conform to the interface, TS should throw an error.

There is no current method of dynamically analyzing an unread JSON file to acquire a type for it.

m_callens
  • 6,100
  • 8
  • 32
  • 54