typescript - 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();
我将不胜感激任何帮助。先感谢您。
解决方案
您的方法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);
}
推荐阅读
- javascript - 在父类javascript中选择标签
- windows - 远程系统服务重启
- amazon-web-services - ElasticBeanstalk `eb setenv` - 应用程序重启
- xamarin - 你如何正确地继承 MvxCollectionViewSource?
- javascript - 创建文件并保存到变量 NodeJS
- c# - 是否允许嵌套模板化控件
- kubernetes - Pod 预设不适用于 minikube
- mysql - SQL:将一行中的所有数据相加
- windows - 使用 Powershell 脚本从批量 Windows 服务器的默认域策略中提取安全设置
- ruby - Ruby - 使用注入的阶乘/组合