繁体   English   中英

从 TypeScript 中的 promise 块中的函数推断类型

[英]Infer type from function in a promise block in TypeScript

我对打字稿很陌生,我想尝试通过创建单行方法来减少我对 try...catch 块的使用。 我遇到的问题是我不知道如何推断或创建一个正确的返回类型,我的 VS 代码强度识别结果值。

我最初试图让它使用泛型类型工作,但我认为这不是正确的方法。

// My try catch block
async function solve<T>(fn: T) {
  const res = await fn;
  if(res)
    return [res, false];
  return [null, true];
}

(async ()=>{
  const [a, b] = await solve(new Promise(resolve => {
    setTimeout(()=>{
      resolve({
        n: 1
      })
    }, 2000)
  }));

  // I want to get suggestion that "n" is a property of returned "a".
  console.log(a)
  // this gives typescript error
  console.log(a.n)

})();

好吧,首先你需要用正确的类型信息注释你的函数和承诺。 所以你的solve方法应该是这样的:

async function solve<T>(fn: Promise<T> | PromiseLike<T>): Promise<[T, false] | [null, true]> {
  const res = await fn;
  if (res)
    return [res, false];
  return [null, true];
}

您应该使用通用Promise<T>调用您的函数:

const [a, err] = await solve(new Promise<{ n: number }>(resolve => {
    setTimeout(() => {
      resolve({
        n: 1
      })
    }, 2000)
  }));

即使你这样做,你也需要一个非空断言来绕过可能的空异常,如下所示:

if (!err) {
    // I want to get suggestion that "n" is a property of returned "a".
    console.log(a)
    // this gives possible null exception but  I think its a limitation.
    console.log(a!.n)
  }

这是 Typescript 的某种限制,它无法根据数组元素正确缩小类型。 如果您使用的是对象而不是数组,它将毫无例外地工作:

async function solve2<T>(fn: Promise<T>): Promise<{ result: T, isError: false } | { result: null, isError: true }> {
  const res = await fn;
  if (res)
    return { result: res, isError: false };

  return { result: null, isError: true };
}

 if (!res.isError) {
    console.log(res.result)
    console.log(res.result.n) // n is inferred correctly and no possible null exception here 
  }

操场

暂无
暂无

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

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