javascript - 模拟 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')
但没有运气。
解决方案
没关系,这解决了它:
export const constructStatesTreeStructure = (
data: StatesRootData = states as StatesRootData,
) => ...
推荐阅读
- json - 如何跟踪“请求产品”或“保存”配置
- javascript - 如何编写涵盖 javascript 文件中 const 的代码测试
- vhdl - VHDL试图将信号作为输入
- next.js - 如果我需要在服务器端和客户端访问它,在哪里存储 jwt 令牌?
- pandas - 在 Pandas 中创建条件语句时需要帮助
- java - 编译器如何识别覆盖方法的返回类型在 Java 中不兼容?
- java - 删除后返回 Java 新值
- reactjs - 调用 auth spotify 时出现 graphql 未知错误
- swiftui - Swiftui iOS14.5 键盘隐藏了 DatePicker 但非常适合 TextField
- java - 寻找有关 java.lang.System.load 的说明