In my Angular / Typescript2.2 project, for development purposes, I import *.json
files from time to time as test data in my components.
To allow importing a .json
file as a module, I added the following to typings.d.ts
declare module '*.json' {
const value: any;
export default value;
}
Of course I can assign the content of these files to a field with type any
, but I want to assign them to a field with type of one of my interfaces instead. Make note that I want to keep the value in the module definition open to all types. I don't want to hard-code it to 1 interface.
import {ProcessMilestone} from '../../../domain';
import * as milestones from './test.json';
export class MilestoneSearchComponent implements OnInit {
data: ProcessMilestone[];
ngOnInit(): void {
this.data = <ProcessMilestone[]> milestones;
}
}
This gives me following error:
Type 'typeof '*.json'' cannot be converted to type 'ProcessMilestone[]>'. Property 'includes' is missing in type 'typeof '*.json''.
It's clear than due to the current module definition of '*.json', casting is not possible. Is it possible to tweak this so that this is possible? I have no idea of the possibilities.
Only minimal-effort solutions are viable. If not, I'll instead fetch the data from the back-end.
Does whatever you're doing work at runtime? If so, you can always force TypeScript to allow a type assertion by passing through any
:
this.data = <ProcessMilestone[]> <any> milestones;
That's as minimal effort as I can think of. Of course if it turns out that your JSON file doesn't contain an object of the right type, it will blow up at runtime with no warning from TypeScript, which has been forced into silence by the type assertion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With