如何使用 TypeScript 为 VSCode 键入 JSON 文件?

How can I type a JSON file with TypeScript for VSCode?

在 Node/TypeScript 项目中,如果我正在使用 VSCode 编辑 tsconfig.jsonpackage.json 文件,那么我会得到编辑器提供的一些有用的智能感知来自打字稿。所以我猜,在某个地方,.d.ts 定义文件和每个文件之间建立了关联以提供此帮助。

我的用例是我必须维护一个项目中的许多 .json 个文件。这些文件由外部工具使用,因此它们不能是 .js.ts 文件。为了使这些文件的编辑更不容易出错,我希望能够编写一个关联的 .d.ts 文件,并以某种方式告诉编辑器这是该 .json 文件的定义文件,然后获取所有编辑器的帮助。

我该怎么做?

或者,tsconfig.jsonpackage.json 定义文件在哪里,VSCode 如何关联它们?

VSCode 可以通过 JSON:

中的 $schema 键使用 JSON 模式
{
  "$schema": "http://json.schemastore.org/coffeelint",
  "line_endings": "unix"
}

Note that this syntax is VS Code-specific and not part of the JSON Schema specification. Adding the $schema key changes the JSON itself, which systems consuming the JSON might not expect, for example, schema validation might fail.

您也可以在设置中定义结构:

"json.schemas": [
    {
        "fileMatch": [
            "/.myconfig"
        ],
        "schema": {
            "type": "object",
            "properties": {
                "name" : {
                    "type": "string",
                    "description": "The name of the entry"
                }
            }
        }
    }
]

VSCode docs