首页 > 解决方案 > 模拟 json 中的文字类型

问题描述

所以我有这个 JSON:

{
  "elements": [
    {
      "type": "abstract"
    },
    {
      "type": "machine"
    },
    {
      "type": "user"
    }
  ]
}

这是我的类型:

export type StateStructure = {
  type: 'user' | 'machine' | 'abstract';
};

但是当我尝试将 JSON 作为数据导入并将其设置为这种类型时,如下所示:

export const constructStatesTreeStructure = (
  data: StatesRootData = states,
) => ...

我收到此错误:

Types of property 'type' are incompatible.
          Type 'string' is not assignable to type '"abstract" | "user" | "machine"'.

这是有道理的。TS 不知道 JSONtype字段中的所有值实际上是这 3 个值之一。但是我如何“转换”它,或“告诉”TS,这些是这个 JSON 中唯一可能的 3 个值?

我试着做某事

type: string & ('user' | 'machine' | 'abstract')

但没有运气。

标签: javascriptjsontypescripttypes

解决方案


没关系,这解决了它:

export const constructStatesTreeStructure = (
  data: StatesRootData = states as StatesRootData,
) => ...

推荐阅读