Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

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

I am writing an app in Angular. I am using json file, by getting data from it in the ts file:

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

And everything is fine. But when I want to add type instead of any:

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

I get an error:

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

This is my interface on service:

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

This is my json file:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The error is correct, because there is no default on Special[].

One easy way to do what you are trying to do is:

Put resolveJsonModule and esModuleInterop in tsconfig.json file of project.

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

and then import:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.7k users

...