1

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

7
  • Are you using Typescript 2+ version? did you add the module declaration in the type definition file? Commented May 20, 2018 at 7:01
  • Also are you using webpack? Commented May 20, 2018 at 7:08
  • In linked example there's "casting" to any, so: export const Dictionary: IDictionary = dictionary as any; Commented May 20, 2018 at 8:09
  • 1
    @AlekseyL. yes I think I can see that that is the problem. By typings.d.ts seems very low level file ad so I did not want to put IDictionary there Commented May 20, 2018 at 8:10
  • 1
    I will check later, but I think you can change import to import dictionary from './dictionary.json'; and no additional casting will be needed (as it is already defined as any) Commented May 20, 2018 at 8:18

2 Answers 2

2

@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;
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.