Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
TypeScript-从函数返回2个不同的接口_Typescript - Fatal编程技术网

TypeScript-从函数返回2个不同的接口

TypeScript-从函数返回2个不同的接口,typescript,Typescript,我想知道如何根据接口返回两种类型的对象 在下面的代码中,声明返回我的函数 : Promise<newEventInt | newWalletInt> currentEvent的错误消息就是那个 Type 'newEventInt' is not assignable to type 'string | number | boolean | Date | undefined'. Type 'newEventInt' is not assignable to type 'strin

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

在下面的代码中,声明返回我的函数

: Promise<newEventInt | newWalletInt>
currentEvent的错误消息就是那个

Type 'newEventInt' is not assignable to type 'string | number | boolean | Date | undefined'.
  Type 'newEventInt' is not assignable to type 'string'.ts(2322)
如果我取下申报表,它就起作用了。但是我想给我的代码更多的保护

提前感谢,, 保罗


您似乎误解了
newEventInt | newWalletInt
的含义。这是一个,允许返回
newEventInt
newWalletInt

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

interface EventAndWallet {
  currentEvent: newEventInt
  wallet: newWalletInt
}

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

Promise不应该是
Promise
?您没有返回并集,而是将两者作为一个对象的两个键返回。但是,我并不真正理解错误消息-除非我遗漏了什么,否则它似乎不应该来自此代码。嘿,VLAZ,感谢您的回复,不幸的是它没有按照您的建议工作
    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
        }
    }
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
}
interface EventAndWallet {
  currentEvent: newEventInt
  wallet: newWalletInt
}