简体   繁体   English

打字稿-“…不是函数或其返回值不可迭代”

[英]Typescript - “… is not a function or its return value is not iterable”

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. 这个函数(理论上)应该可以帮助我在函数中使用await时发现错误。 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 to不是函数或其返回值不可迭代

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[]> 尽管预期的返回签名应为Promise<[Error, null]> Promise<[null, Error]> ,但它看起来像返回(理论上,因为它实际上失败了): Promise<any[] | Error[]> Promise<any[] | Error[]> : Promise<any[] | Error[]>

发挥作用

What am I missing? 我想念什么?

I think the problem is caused by duck typing, TypeScript is not able to guess the return type correctly from the expressions. 我认为问题是由鸭子输入引起的,TypeScript无法从表达式中正确猜测返回类型。

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]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 useContext 不是 function 或其返回值不可迭代 - useContext is not a function or its return value is not iterable “'x' is not a function or its return value is not iterable”的含义错误 - The meaning of “'x' is not a function or its return value is not iterable” error 类型错误:object 不是 function 或其返回值在反应 16.13.1 中不可迭代 - Typerror: object is not a function or its return value is not iterable in react 16.13.1 Firebase:snapshot.val不是函数或其返回值不可迭代 - Firebase: snapshot.val is not a function or its return value is not iterable (WebPack) TypeError: Object is not a function or its return value is not iterable - (WebPack) TypeError: Object is not a function or its return value is not iterable TypeError: react__WEBPACK_IMPORTED_MODULE_1___default 不是 function 或其返回值不可迭代 - TypeError: react__WEBPACK_IMPORTED_MODULE_1___default is not a function or its return value is not iterable 返回值不可迭代 - Return value is not iterable 打字稿返回值或咖喱函数 - Typescript return value or curried function 如何将 function 或其返回值从 typescript (.ts) 导入 javascript (.js) - How to import a function or its return value from typescript (.ts) to javascript (.js) TypeScript - 从回调 function 返回 function 值 - TypeScript - Return function value from the callback function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM