简体   繁体   English

object 中的类型从异步 function 返回 Typescript

[英]Types in object destructing from async function return in Typescript

Given a function that returns an object promise with a boolean & string:给定一个 function 返回一个 object promise 和 Z84E2C64F38F78BA3EA5C905AB5A2DA7

const test = () => {
   return new Promise(async (resolve) => {
       resolve({ result: false, error: 'This is an error' });
   })
}

I try to destruct these couple of values into constants:我尝试将这两个值破坏为常量:

const { result, error } = await test();

However, I always get these Typescript errors:但是,我总是收到这些 Typescript 错误:

Property 'result' does not exist on type 'unknown'.ts(2339)
Property 'error' does not exist on type 'unknown'.ts(2339)

I've tried all kinds of combinations, but the only one working is adding the 'any' type, which I believe we should always avoid.我尝试了各种组合,但唯一有效的是添加“任何”类型,我相信我们应该始终避免。

Any idea to define the right types without getting error?有什么想法可以定义正确的类型而不会出错吗?

Here you should add the type as the generic parameter to the promise - ie new Promise<MyType>(...) Example:在这里,您应该将类型作为通用参数添加到 promise - 即new Promise<MyType>(...)示例:

type MyPromiseResult = { result: boolean, error: string };

const test = () => {
   return new Promise<MyPromiseResult>((resolve) => {
       resolve({ result: false, error: 'This is an error' });
   })
}

async function doThing() {
  const { result, error } = await test();
  type ResultType = typeof result; // boolean
  type ErrorType = typeof error; // string
}

Give your response a type给你的回复一个类型

return new Promise<{ result: boolean, error: string }>((resolve) => {})

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM