Simon H
Simon H

Reputation: 21005

(Typescript) Import json into Angular 4 project

I have a json file of translations that I want to use in my angular 4 project. The file is also used in php which is why it needs to be stored as json rather than as a js module.

It has this structure

export interface IDictionary {
    amsterdamCenter: number[];
    amsterdamBounds: Array<number[]>;
    prices: Price[];
    cuisines: Object;
    areas: Object;
}

Following https://hackernoon.com/import-json-into-typescript-8d465beded79 I have changed typings.d.ts to read

/* SystemJS module definition */
declare var module: NodeModule;
interface NodeModule {
  id: string;
}

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

Now I have an error with

import * as dictionary from './dictionary.json';

export const Dictionary: IDictionary = dictionary;

[ts] Type 'typeof ".json"' is not assignable to type 'IDictionary'. Property 'amsterdamCenter' is missing in type 'typeof ".json"'.

However

export const Dictionary: any = dictionary;

does work. I'm hoping there is an incantation of TS that will permit me to import typescript using my interfaces

Upvotes: 1

Views: 1453

Answers (2)

Jhonycage
Jhonycage

Reputation: 859

One thing you could do is parse the Json file like :

import * as myJson from './my-json.json';

getMyJson(): Array<any> {
 return JSON.parse(JSON.stringify(myJson))
}

you can type the response to a specific model/class if you wish.

EDIT: Actually just import and assign, copy if you wish:

import * as settingsMenu from './settings-menu.json';
const array = settingsMenu;
// OPTIONAL: copy object
const menu: Array<BdbMap> = new Array();
Object.assign(menu, array);

Upvotes: 1

Senthil
Senthil

Reputation: 777

@simon-h try this code. Its working fine

import * as dictionary from './dictionary.json';

export const Dictionary: IDictionary = (<any>dictionary);

(or)

export const Dictionary: any = (<any>dictionary);

(or)

export const Dictionary: any = dictionary as any;

Upvotes: 3

Related Questions