首页 > 解决方案 > TypeScript 如何将对象数组转换为具体模型?

问题描述

我在下面有一个简单的示例,我想将对象数组转换为 Animal 对象数组,但Type 'Animal[]' is missing the following properties from type 'Promise<Animal[]>': then, catch, [Symbol.toStringTag]Controller.getPersons()函数中出现此错误。我不完全确定是什么导致了这个错误。

class Animal {
  name: string;
  colour: string;

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

我有这个函数的类,它承诺返回一个 Animal 对象的数组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;
  }

这是我要转换为 Animal 对象数组的示例数据

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

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

我将不胜感激任何帮助。先感谢您。

标签: typescript

解决方案


您的方法getPersons()的返回类型为Promise<Animal[]>. 但是,您实际上返回的只是一组动物。

正如@ttugates 在评论中指出的那样,您有两种选择:

更改返回类型

更改方法的返回类型Animal[]以匹配实现:

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

改变实施

如果你真的需要一个promise,可能要符合某个接口,创建一个并返回它:

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);
}

推荐阅读