1

i have a config.json file

{
  "profiler": {
    "port": 8001,
    "profilerCache": {
      "allowedOriginsRegex": ["^http:\/\/localhost:8080$", "i"]
    }
  },
  "database": {
    "uri": "mongodb+srv://...",
    "dbName": "profiler",
    "collectionName": "profiles"
  }
}

at build time, i want to see errors if the json structure doesn't match my interface for it

export interface Config {
  port: number
  profilerCache: {
    allowedOriginsRegex: [string, string]
  }
  database: {
    uri: string
    dbName: string
    collectionName: string
  }
}

what's the simplest way to accomplish type safety for my json files?

ChaseMoskal
  • 7,151
  • 5
  • 37
  • 50
  • You can create a temp file like `let x: Config = your-json` and compile it, see e.g. https://stackoverflow.com/a/57942560/989121 – georg Sep 22 '19 at 20:16

1 Answers1

0

Assigning the JSON object to a variable of the interface type will show structural errors.

export interface Config {
  port: number
  profilerCache: {
    allowedOriginsRegex: [string, string]
  }
  database: {
    uri: string
    dbName: string
    collectionName: string
  }
}

let jsonConfig: Config = {
  "port_error": 8001,  // Error: Object literal may only specify known properties, and '"port_error"' does not exist in type 'Config'.
  "profilerCache": {
    "allowedOriginsRegex": ["^http:\/\/localhost:8080$", "i"]
  },
  "database": {
    "uri": "mongodb+srv://...",
    "dbName": "profiler",
    "collectionName": "profiles"
  }
}

See Typescript Playground Example

Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117
  • i'd like my `config.json` to actually be an json file — not a typescript file which contains some json — i'm hoping the authoritative `config.json` can be ingested/manipulated by other tools which are familiar with json (but not typescript) – ChaseMoskal Sep 22 '19 at 20:11
  • @ChaseMoskal If you want to verify the JSON structure at **runtime**, see [**Check if an object implements an interface at runtime with TypeScript**](https://stackoverflow.com/q/33800497/1164465). – Christopher Peisert Sep 22 '19 at 20:16