【问题标题】:Verify JSON file matches TypeScript Interface验证 JSON 文件是否匹配 TypeScript 接口
【发布时间】:2019-09-22 19:33:35
【问题描述】:

我有一个config.json 文件

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

在构建时,如果 json 结构与我的接口不匹配,我想查看错误

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

为我的 json 文件实现类型安全的最简单方法是什么?

【问题讨论】:

标签: json typescript


【解决方案1】:

JSON 对象分配给接口类型的变量会显示结构错误。

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"
  }
}

Typescript Playground Example

【讨论】:

  • 我希望我的 config.json 实际上是一个 json 文件——而不是包含一些 json 的打字稿文件——我希望权威的 config.json 可以被其他工具摄取/操作熟悉 json(但不熟悉 typescript)
  • @ChaseMoskal 如果您想在运行时验证 JSON 结构,请参阅Check if an object implements an interface at runtime with TypeScript
猜你喜欢
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
  • 2018-11-18
相关资源
最近更新 更多