0

我想知道如何根据它们的接口返回两种类型的对象。

进入下面的代码,我的函数的声明返回

: Promise<newEventInt | newWalletInt>

使我返回的两个值都加下划线

return {
        currentEvent, 
        wallet
    }

currentEvent 的错误消息是那个

Type 'newEventInt' is not assignable to type 'string | number | boolean | Date | undefined'.
  Type 'newEventInt' is not assignable to type 'string'.ts(2322)

如果我取消声明的退货,它正在工作。但我想给我的代码更多的保护。

提前谢谢,保罗

    private async isEventOwnedByUser(userId: number, eventId: number): Promise<newEventInt | newWalletInt> {
        // get event + handling error
        const currentEvent: newEventInt = await this.event.findOne(eventId)            
        if (!currentEvent) throw new Error(`This event does not exist`);

        //  get user's wallet + handling error
        const wallet: newWalletInt = await this.wallet.getOneWalletByUserId(currentEvent.wallet_id, userId)   
        if (!wallet) throw new Error('This event does not exist')

        return {
            currentEvent, 
            wallet
        }
    }

newEventInt 接口

export interface newEventInt {
    [key: string]: number | string | Date;

    type: string,
    date: Date,
    quantity: number,
    total_amount: number,
    unit_price: number,
    fees: number,
    note: string,
    platform_sending: string,
    platform_receiving: string,
    currency_asset: string,
    currency_counterparty: string,
    currency_fees: number,
    wallet_id: number,
    ref_usd_amount: number,
    ref_usd_fees: number,
    created_at: Date
}
4

1 回答 1

1

你似乎误解了 的意思newEventInt | newWalletInt。这是一个联合类型,它允许返回 anewEventInt或 a newWalletInt

但是,您的函数返回其他内容:具有两个属性的对象,每种类型一个。这个对象实现了这个接口:

interface EventAndWallet {
  currentEvent: newEventInt
  wallet: newWalletInt
}

因此,如果您定义该接口并将函数的返回类型更改为Promise<EventAndWallet>您的错误应该消失。

于 2020-11-24T09:43:28.710 回答