0

I have this simple example below where I want to convert an array of objects to an array of Animal objects but I get this error Type 'Animal[]' is missing the following properties from type 'Promise<Animal[]>': then, catch, [Symbol.toStringTag] in the Controller.getPersons() function. I am not entirely sure what is causing this error.

class Animal {
  name: string;
  colour: string;

  constructor(name: string, colour: string) {
    this.name = name;
    this.colour = colour;
  }
}

The class where I have this function which promise to return an array of Animal objects getPersons(): Promise<Animal[]>

class Controller {
  data: { name: string; colour: string }[];

  constructor(data: { name: string; colour: string }[]) {
    this.data = data;
  }

  getPersons(): Promise<Animal[]> {
    const animals = this.data.map(a => new Animal(a.name, a.colour));
    console.log("animals -----> ", animals);
    console.log("type -----> ", typeof animals);
    return animals;
  }

This is my sample data which I want to convert to an array of Animal objects

const data = [
   { name: "Dog", colour: "Black" },
   { name: "Cat", colour: "White" }
];

const c = new Controller(data);
c.getPersons();

I would appreciate any help. Thank you in advance.

1
  • 2
    I believe your issue is you are returning Animal[] as opposed to Promise<Animal[]>. Either alter the return type of Promise<Animal[]> to be Animal[] or update data to return a promise. Commented Sep 7, 2019 at 16:09

1 Answer 1

1

Your method getPersons() has a return type of Promise<Animal[]>. However what you're actually returning is just an array of animals.

As @ttugates points out in the comments, you have two options:

Change the return type

Change the return type of the method to Animal[] to match the implementation:

getPersons(): Animal[] {
    // ...
}

Change the implementation

If you really need a promise, possibly to conform to a certain interface, create one and return it:

getPersons(): Promise<Animal[]> {
    const animals = this.data.map(a => new Animal(a.name, a.colour));
    console.log("animals -----> ", animals);
    console.log("type -----> ", typeof animals);
    return Promise.resolve(animals);
}
Sign up to request clarification or add additional context in comments.

Comments

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.