簡體   English   中英

錯誤 TS2339:“特殊 []”類型上不存在屬性“默認”

[英]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[];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM