Shehab Eltawel
Shehab Eltawel

Reputation: 123

Angular Promise<void>' is not assignable to type

I am building Angular4 website using Contentful CMS API to retrieve data. The problem is I cannot assign the right types for the returned data even thought the console shows those types.

the Mock data:

export const NAMES: Page[] = content.getEntries({
    content_type: 'mainMenu'
}).then(function(response){
 response.items.forEach(element => {
   return element.fields;  
 })
});

Which is return via the console (If is used console.log ) :

Object { title: "About Aliens" }
Object { title: "Portfolio" }
Object { title: "Meet the team" }
Object { title: "Contact us" }

and the class I use to assign those data types :

export class Page {
  title: string;
}

I am new to Typescript and I want to know where I got wrong and I would appreciate it if someone guided me where I can go to master returning such data from any API.

Thank you.

Upvotes: 0

Views: 1946

Answers (2)

Igor
Igor

Reputation: 62298

  1. You are trying to assign a promise to an array, you have to do the assignment in the callback of the promise.
  2. Your then call on the promise does not return anything, a call to forEach iterates over a collection but returns nothing. If you want to create/return something you could use map which creates a new collection based on the passed in predicate.
  3. Use an arrow function for the promise callback so you have a reference to this should you need it.
  4. There is no need to make Page a concrete type, use an interface instead so you can use casting. You only need a concrete type if you are going to add behavior but if its just a plain old object that is deserialized from json use an interface.

The fix:

export NAMES: IPage[]; // no assignment at this point

Execute getEntries from within some method.

content.getEntries({
    content_type: 'mainMenu'
}).then((response) => {
   NAMES = response.items.map(element => element as IPage);
});

IPage

export interface IPage {
  title: string;
}

Upvotes: 2

nagrom97
nagrom97

Reputation: 514

Make your page class an interface for type assertion without the need for instantiation, like so

export interface Page { title : string }

Upvotes: 0

Related Questions