因此,我看到了一些关于这是否可能的相互矛盾的结果.通过搜索,我在这里找到了一些线索,声明不可能在运行时使用TypeScrip进行模式验证.

然而,我最近也读到,您可以通过使用TypeScrip的"类型断言"来做到这一点.类似于此的内容:

interface User {
  firstName: string
  lastName: string
  email: string
}

然后做这样的事情(例如,做API测试)

const response = await fetch("someUrlthatReturnsaUser")
const json = response.text()
const user = JSON.parse(json) as User

这大概不会给您提供IDE中的任何信息或任何东西,但它可能会失败?如果它与架构不匹配.

这是可能的,甚至是正确的方式吗?这似乎类似于C#中的反序列化或类似的东西.

推荐答案

可以使用JS在运行时进行类型判断,但这需要一些工作,因为从编译后的代码中删除了类型脚本.它需要两个步骤:

Generate a JSON Schema from your User interface

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "firstName": {
      "type": "string"
    },
    "lastName": {
      "type": "string"
    },
    "email": {
      "type": "string"
    }
  },
  "required": [
    "firstName",
    "lastName",
    "email"
  ]
}

Use a type-safe schema validator to validate your data

const data = parse(json) // User | undefined
if (data === undefined) {
    console.log(parse.message) // error message from the last parse call
    console.log(parse.position) // error position in string
  } else {
    // data is User here
    console.log(user.firstName)
  }
}

这些步骤中的每一步都有多个工具可用.我所链接的只是一些例子.你可以玩https://www.jsonschemavalidator.net/

Json相关问答推荐

输入请求中不存在null的条件抖动

Vega-Lite:文本笔画在外部

从Json响应中为需要每个值的Post请求提取多个值

震击:三针并用震击

Azure Data Factory JSON输出格式问题

盒子图显示不正确

无法从JSON解析ZonedDateTime,但可以使用格式化程序很好地解析

属性错误:';ActivitiesClient';对象没有属性';base_url';

PowerShell - 将 json 添加到文件内容

ETCD 导出为 json 并从 base64 解码所有键/值到人类可读

将具有多个级别的 json 读入 DataFrame [python]

如果 JSON 对象包含列表中的子字符串,则丢弃它们

使用 jq Select 键:值并输出为数组

在 postgresql 中将行转换为 json 对象

以 JSON 格式访问(新型、公共)Google 工作表

有必要清理 JSON 吗?

在浏览器中查看 JSON 文件

如何从 JSON 响应中提取单个值?

使用 C# 调用 json

来自 Gson 的 JSON 字符串:删除双引号