错误 TS2339:属性 'default' 在类型 'Special[]' 上不存在

Error TS2339: Property 'default' does not exist on type 'Special[]'

我正在 Angular 中编写应用程序。我正在使用 json 文件,通过在 ts 文件中从中获取数据:

import * as data from '../../special.json';
export class SpecialComponent {
  specials = (data as any).default;
}

一切都很好。但是当我想添加类型而不是任何类型时:

import * as data from '../../special.json';
export class SpecialComponent {
  specials = (data as Special[]).default;
}

我得到一个错误:

error TS2339: Property 'default' does not exist on type 'Special[]'.

这是我的服务界面:

export interface Special {
  category: string;
  name: string;
  description: string;
  type?: string;
  imageUrl?: string;
}

这是我的 json 文件:

[
    {
        "category": "xxx",
        "name": "xxx",
        "description": "xxx",
        "type": "xxx",
        "imageUrl": [
            "assets/img/img.jpg",
            "assets/img/img1.jpg"
        ]
    }
]

错误是正确的,因为Special[]上没有default

一个简单的方法来做你想做的事情是:

resolveJsonModuleesModuleInterop 放入项目的 tsconfig.json 文件中。

"compilerOptions": {
  "resolveJsonModule": true,
  "esModuleInterop": true,
  ....
}

然后导入:

import {default as data} from '../../special.json';
export class SpecialComponent {
  specials = data as Special[];
}