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

时间:2018-06-19 09:37:26

标签: json typescript typescript2.0

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

{"test":[
    {"file": "f1.txt", "nr":3},
    {"file": "f4.txt", "nr":4},
    {"file": "f7.txt", "nr":7}
]}

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

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

interface FileEntity{
    file: string;
    nr: number;
}

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

declare module "*.json" {
    const value: any;
    export default value;
}

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

import * as b from '../../assets/test.json';
let files: IJsonFiles;
files = b;

这会导致以下错误:

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

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

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

3 个答案:

答案 0 :(得分:1)

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

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

import * as b from '../../assets/test.json';
let files: IJsonFiles = <IJsonFiles> b;

答案 1 :(得分:0)

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

venues.json

[
  {
    "id": "c29e3ee4b23342db8afdab4c826ab478",
    "name": "Example",
    "hostnames": [
      "example.com"
    ],
    "shortcode": "example",
    "lickstatsUrl": "https://theregs.co/example",
    "pin": "1234"
  },
  ...
]

index.ts

import _venues from './venues.json';

interface Venue {
  id: string;
  hostnames: string[];
  shortcode: string;
  lickstatsUrl: string;
  pin: string;
}

const venues = _venues as Venue[];

答案 2 :(得分:0)

您可以使用接口声明新对象。您的情况将是下一个:

import venuesRaw from './venues.json';

interface IVenue {
  id: string;
  hostnames: string[];
  shortcode: string;
  lickstatsUrl: string;
  pin: string;
}

const venues: Venue = venuesRaw;