首页 > 解决方案 > 打字稿 - 面临的问题属性不能分配给基本类型中的相同属性

问题描述

我在打字稿中遇到问题。我创建了两个接口,一个用于类,另一个用于在类中定义的函数。这是我的 Schedule 类的接口

interface scheduleClass { 
getScheduleLists(): showListsInterface
}

这是我的显示列表功能的界面。

interface showListsInterface {
  status: string;
  statusCode: number;
  message: string;
  data: Promise<Schedule[]>
}

这是时间表类

export class scheduleServices implements scheduleClass{
async getScheduleLists(){
    try {
        const schedules = await Schedule.findAll();
        return {
            status:"success",
            statusCode:200,
            message:"",
            data:schedules
        }
    } catch (error) {
        return {
            status:"error",
            statusCode:500,
            message:error.message,
            data:[]

        }
    }

}

有人可以解释我做错了什么吗?

标签: javascriptnode.jstypescript

解决方案


您的返回类型不正确。async函数总是返回 a Promise,但你的类型是一个对象,其中有一个承诺。它需要是对整个事情的承诺。

我会在没有承诺的情况下制作类型:

interface showListsInterface {
  status: string;
  statusCode: number;
  message: string;
  data: Schedule[];
}

那么函数的返回类型是Promise<showListsInterface>.

我本来想说“或更改函数以返回带有承诺的对象”,但我看到对象的其他部分依赖于知道异步部分是否有效,因此在这种特定情况下这不是一个选项。


推荐阅读