5

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.

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm and very minimal indeed! Never tried a double type assertion. Thanks!

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.