提问人:Jan Svatoň 提问时间:8/3/2023 更新时间:8/3/2023 访问量:24
TypeScript:导入的 JSON 数据类型推理问题
TypeScript: Imported JSON Data Type Inference Issue
问:
在将 JSON 数据导入我的 ReactApp 时,我遇到了 TypeScript 的奇怪行为。 当我有一个包含以下代码的中间文件时: 接口.tsx
import { Node } from "relatives-tree/lib/types"
import data from "./data.json";
export const SOURCE = data as readonly Readonly<Node>[];
然后我在我的应用程序中导入此代码,它就像一个魅力,但是,当我尝试直接在我的应用程序中导入数据时:
import DataFamily from "../data.json";
//THIS WILL NOT WORK
const data: Readonly<Node[]> = DataFamily;
数据变量收到错误类型“{}”缺少类型“readonly Readonly<{ id: string; gender: Gender; parents...中的以下属性。
节点类型定义为
export declare type Node = Readonly<{
id: string;
name: string;
isAffected: boolean;
gender: Gender;
parents: readonly Relation[];
children: readonly Relation[];
siblings: readonly Relation[];
spouses: readonly Relation[];
placeholder?: boolean;
}>;
我在这里错过了什么?此外,在我看来,使用中间文件是绕过类型检查的一种方式 - 在沙箱(下面的链接)中,我编辑了一个成员的 id 是整数而不是字符串的数据,并且代码仍然有效。
https://codesandbox.io/s/adoring-jones-tz7mrp?file=/src/components/App/App.tsx
我试图用ChatGPT弄清楚,但他没有希望。对我来说,在应用程序中直接导入 JSON 数据应该与从中间文件导入数据一样有效
答: 暂无答案
评论