相关疑难解决方法(0)

你如何在async catch()中使用类型错误

我正在使用一个async函数来调用现有的基于promise的API,该API拒绝带有类型错误的promise.

你可以像这样模仿这种行为:

interface ApiError {
  code: number;
  error: string;
}

function api(): Promise<any> {
  return new Promise((resolve, reject) => {
    reject({ code: 123, error: "Error!" });
  });
}
Run Code Online (Sandbox Code Playgroud)

现在有了promises,我可以将错误类型注释为ApiError:

api().catch((error: ApiError) => console.log(error.code, error.message))
Run Code Online (Sandbox Code Playgroud)

但是在使用时,async如果我尝试在以下位置注释错误类型try ... catch():

async function test() {
  try {
    return await api();
  } catch (error: ApiError) {
    console.log("error", error);
  }
}
Run Code Online (Sandbox Code Playgroud)

它编译错误:

Catch子句变量不能有类型注释.

那么,我怎么知道我期待的是什么样的错误?我需要在catch()块中写一个断言吗?这是异步的错误/不完整功能吗?

typescript

15
推荐指数
4
解决办法
3949
查看次数

标签 统计

typescript ×1