TypeScript - 导入 JSON 文件并分配给使用接口声明的变量

Mae*_*cky 6 json typescript typescript2.0

我有以下 JSON 文件(test.json):

{"test":[
    {"file": "f1.txt", "nr":3},
    {"file": "f4.txt", "nr":4},
    {"file": "f7.txt", "nr":7}
]}
Run Code Online (Sandbox Code Playgroud)

我在 TypeScript 中为这个 JSON 结构定义了一个接口:

export interface IJsonFiles {
    test: (FileEntity)[];
}

interface FileEntity{
    file: string;
    nr: number;
}
Run Code Online (Sandbox Code Playgroud)

为了使导入语句在 TS 中工作,我必须创建一个包含以下内容的 json.d.ts 文件:

declare module "*.json" {
    const value: any;
    export default value;
}
Run Code Online (Sandbox Code Playgroud)

然后我将 test.json 导入到我的代码中,如下所示:

import * as b from '../../assets/test.json';
let files: IJsonFiles;
files = b;
Run Code Online (Sandbox Code Playgroud)

这会导致以下错误:

TS2322: Type 'typeof import("*.json")' is not assignable to type 'IJsonFiles'.  Property 'test' is missing in type 'typeof import("*.json")'.
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?本质上,我想要实现的是:

我想从文件系统中导入 JSON 文件(不想使用 require!),我想在 TS 中定义 JSON 结构(没有隐含的任何......)。

sun*_*sen 12

这就是我在 Node v10.16.0 和 TypeScript v3.6.3 上导入 JSON 并向其添加类型定义的方式。

场地.json

[
  {
    "id": "c29e3ee4b23342db8afdab4c826ab478",
    "name": "Example",
    "hostnames": [
      "example.com"
    ],
    "shortcode": "example",
    "lickstatsUrl": "https://theregs.co/example",
    "pin": "1234"
  },
  ...
]
Run Code Online (Sandbox Code Playgroud)

索引.ts

[
  {
    "id": "c29e3ee4b23342db8afdab4c826ab478",
    "name": "Example",
    "hostnames": [
      "example.com"
    ],
    "shortcode": "example",
    "lickstatsUrl": "https://theregs.co/example",
    "pin": "1234"
  },
  ...
]
Run Code Online (Sandbox Code Playgroud)

  • 到 2022 年就没有更好的方法了吗? (8认同)

tok*_*iyu 5

Typescript 2.9 支持开箱即用的类型良好的 JSON 导入。https://blogs.msdn.microsoft.com/typescript/2018/05/31/annoucing-typescript-2-9/#json-imports

编辑。您也可以将b变量转换为IJsonFiles类型。

import * as b from '../../assets/test.json';
let files: IJsonFiles = <IJsonFiles> b;
Run Code Online (Sandbox Code Playgroud)

  • 我按照您的建议做了,这给了我:解析为非模块实体,并且无法使用此构造导入。但是 import b = require('../../assets/test.json'); 作品。我不明白为什么。 (2认同)