Recently, I came across an article on that mentioned the possibility of importing JSON objects into a TypeScript project. Intrigued, I decided to give it a try by importing the following JSON:
{
"defaultLanguage": "en",
"languageMap": {
"en": "English",
"pl": "Polish",
"de": "German"
}
}
To ensure that future changes to this JSON file do not break my application, I created an interface for the imported object:
export default interface IConfig {
defaultLanguage: string;
languageMap: ILanguage
}
interface ILanguage {
[language: string]: string
}
I then proceeded to update the typings.d.ts file:
declare module "*.json" {
const value: any;
export default value;
}
Next, I imported the JSON file into my Angular component:
import IConfig from './IConfig'; // Attempted to use IConfig as a type in various places.
import * as config from './config.json';
(...)
private languageMap = config.languageMap; // At this point, Visual Studio Code flagged 'languageMap' with the error:
// [ts] Property 'languageMap' does not exist on type 'typeof "*.json"'.
[ts] Property 'languageMap' does not exist on type 'typeof "*.json"'.
Additionally, the following error popped up:
any
Is there a way to avoid using (<any>config).languageMap
and instead utilize my IConfig interface, as suggested in the aforementioned link?