javascript - Typescript - "... is not a function or its return value is not iterable" - Stack Overflow

I have this helper function:export function to(promise: Promise<any>) {return promise.then((data:

I have this helper function:

export function to(promise: Promise<any>) {
  return promise
    .then((data: any) => [null, data])
    .catch((err: Error) => [err, null]);
}

This function (in theory) should help me catch errors while using await in functions. for example:

const [err, data] = await to(validate(card));

The problem is that on runtime, I get the following error:

to is not a function or its return value is not iterable

While the expected return signature should be Promise<[Error, null]> Promise<[null, Error]>, it looks like returns (again, in theory, because it actually fails): Promise<any[] | Error[]>:

What am I missing?

I have this helper function:

export function to(promise: Promise<any>) {
  return promise
    .then((data: any) => [null, data])
    .catch((err: Error) => [err, null]);
}

This function (in theory) should help me catch errors while using await in functions. for example:

const [err, data] = await to(validate(card));

The problem is that on runtime, I get the following error:

to is not a function or its return value is not iterable

While the expected return signature should be Promise<[Error, null]> Promise<[null, Error]>, it looks like returns (again, in theory, because it actually fails): Promise<any[] | Error[]>:

What am I missing?

Share Improve this question edited Mar 19, 2019 at 7:02 Eliya Cohen asked Mar 19, 2019 at 6:56 Eliya CohenEliya Cohen 11.5k14 gold badges76 silver badges124 bronze badges 4
  • 1 I assume your validate call should be a call to to, right? – ShamPooSham Commented Mar 19, 2019 at 7:00
  • @ShamPooSham you're right. My mistake. I have updated my question – Eliya Cohen Commented Mar 19, 2019 at 7:02
  • Can you put together an small example where this happens? – distante Commented Mar 19, 2019 at 7:07
  • 1 I got exactly the same error in pure Javascript due to a branch in the called function which mistakenly returned a single element instead of an array. – Craig Hicks Commented Aug 11, 2019 at 15:53
Add a ment  | 

1 Answer 1

Reset to default 4

I think the problem is caused by duck typing, TypeScript is not able to guess the return type correctly from the expressions.

You can type it explicit:

function to(promise: Promise<any>): Promise<[Error, any]> {
    return promise
        .then((data: any) => [null, data] as [Error, any])
        .catch((err: Error) => [err, null] as [Error, any]);
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742281121a4414496.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信