0

I have a json file and I created an interface. But when I did http request, I do access the data but my typescript compiler is complaining.

    "movies": [
        {
          "title": "Tripple Frontier",
          "id": "1",
          "actors":[],
          "url": "assets/images/netflix-names/220px-Triple_Frontier.jpg",
          "producer": "",
          "releaseDate": "new Date('24/6/2017')"
        },
        {
         "title":"In the name of the father",
         "id": 2,
          "actors":[],
          "url": "assets/images/netflix-          names/In_the_name_of_the_father.jpg",
          "producer": "",
          "releaseDate": "new Date('15/8/2018')"
        }
  ]

 //Model

    export interface IMovie {
        title: string;
        id: number;
        actors: [];
        url: string;
        producer: string;
        releaseDate: Date
    } 

   @Injectable()
      export class MovieService {
      moviesUrl: string = '../assets/movies.json';
      constructor(private _http:HttpClient) {
     }
    getMovies():Observable<IMovie[]> {
         return this._http.get(this.moviesUrl).pipe(
           map(response => <IMovie[]>response.movies)
          )
       }
    }

Compiler tells me that

property movies does not exist in type object

How can I define the interface so that the typescript compiler will recognize the movies property that is return even though the code runs well ?

Mickaël Leger
  • 3,426
  • 2
  • 17
  • 36
pedroyanky
  • 323
  • 2
  • 10
  • For a start, you should use the `as` syntax instead of the angle bracket syntax for type assertions: https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions. Secondly, you shouldn't store raw JavaScript code inside of JSON - this may pose as a security vulnerability especially if the JavaScript code in the JSON file was malicious code which would be parsed by the compiler. Instead, consider storing a string representation of a Date object. See https://www.w3.org/TR/NOTE-datetime for more info. (Btw, the compiler won't correctly interpret your string as a Date object) – Edric Oct 31 '19 at 15:21
  • map((response: IMovie[]) => response.movies) ? – Darren Lamb Oct 31 '19 at 15:22
  • @DarrenLamb I'm pretty sure the OP is trying to define `IMovie` on the `movies` property of the JSON file that he has, not the root of the JSON file. – Edric Oct 31 '19 at 15:25
  • Also you JSON isnt valid. It will need to be wrapped in braces e.g { "movies" : [ ... ] } – Darren Lamb Oct 31 '19 at 15:32
  • My problem is how I might define the interface, so as to get the movies via http calls – pedroyanky Oct 31 '19 at 15:43

0 Answers0