Typescript 中的 JSON 接口是什么

What is the JSON interface in Typescript

为什么以下代码片段无法编译,ES6 JSON 接口应该如何使用?

let myVar: JSON = {"id": "12"};

给出以下错误信息:Type '{ id: string; }' is not assignable to type 'JSON'. Object literal may only specify known properties, and '"id"' does not exist in type 'JSON'.

我的IDE对JSON给出了如下定义,但是我看不懂:

interface JSON {
    readonly [Symbol.toStringTag]: string;
}

JSON 是一个全局对象 defined by the JS specification,旨在保存 parsestringify 方法,用于在 JS 数据结构和 JSON 文本之间进行转换。

这不是一个类型。它不应该被用作一个。


创建自定义对象格式时,您应该定义自己的类型(虽然在这里这样做没有用,但如果您在其他地方定义一个函数,您可能需要将对象传递给 as一个论点)。当处理 JSON 时,你正在处理字符串。

type MyFormat = {
    id: string;
}

let myVar: MyFormat = {"id": "12"};
let myJSON: string = JSON.stringify(myVar);

您没有理由在代码中使用 JSON 接口。它与 JSON built-in 对象相关,除了使用其 parse and/or stringify 方法解析或创建 JSON文本。

从您的代码来看,您似乎误解了 JSON 是什么。 (很多 人!:-))JSON 是一种用于数据交换的文本符号(More here.) 如果您处理的是 JavaScript 或 TypeScript 源代码,而不是处理 字符串,则您不是在处理 JSON。

您的 myVar 指的是一个 对象 。没有必要在它上面放一个类型注释,你可以让 TypeScript 从初始化程序中推断它,但是如果你想在它上面放一个类型注释,你可以使用 {id: string;}Record<string, string> 或其他一些 object type:

// Letting TypeScript infer
let myVar = {"id": "12"};
// Or specify an object with an `id` property of type string
let myVar: {id: string;} = {"id": "12"};
// Or create a type alias and use it
type MyVarType = {
    id: string;
};
let myVar: MyVarType = {"id": "12"};
// Or perhaps an object where any string is a valid property name and the types are all strings
let myVar: Record<string, string> = {"id": "12"};

有关对象类型的更多信息,请参阅上面的 documentation 链接。


旁注:如果您打算为 id 使用数字,则应使用 id: number 或类似的:

let myVar: {id: number;} = {id: 12};