Typescript用于异步

Typescript用于异步,typescript,Typescript,怎么做 //无法更改 声明类型NextApiRequest={ 查询:{ [键:string]:string | string[]; }; 曲奇饼:{ [键:字符串]:字符串; }; 机构:任何; }; 接口NextApiRequestEx扩展了NextApiRequest{ 身体:T; } 类型Bar={Bar:string}; const isValid=async(req:NextApiRequest):req为NextApiRequestEx=>true; 声明const-req:N

怎么做

//无法更改
声明类型NextApiRequest={
查询:{
[键:string]:string | string[];
};
曲奇饼:{
[键:字符串]:字符串;
};
机构:任何;
};
接口NextApiRequestEx扩展了NextApiRequest{
身体:T;
}
类型Bar={Bar:string};
const isValid=async(req:NextApiRequest):req为NextApiRequestEx=>true;
声明const-req:NextApiRequest;
if(isValid(req)){
请求正文栏
}
错误:

异步函数或方法的返回类型必须是全局类型 承诺型


标记为
async
的函数必须被键入为返回承诺,因为JS保证函数在调用时将返回承诺,而不管函数体是什么

这有点复杂,因为您使用的是不能异步的typeguard。处理这个问题的一个策略是使typeguard同步,并让它接收预先等待的结果,否则它可能会等待这些结果

例如

// what we'd like to do, obviously a contrived example
async isSomething(t: Something | OtherThing): t is Something {
  const result = await someCall(t); // some async result we need to determine what t is
  return result.isSomething;
}
这可以更改为

async isSomethingAsyncPart(t: Something | OtherThing): IsSomethingAsyncResultSet {
  // do some await'ing here
  return asyncResults; 
}
isSomethingGuard(t: Something | OtherThing, asyncResults: IsSomethingAsyncResultSet): t is Something {
  // some synchronous evaluation using t and/or asyncResults
}

// kinda yucky but :shrug_emoji:
if (isSomethingGuard(t, await isSomethingAsyncPart(t)) { . . .}
不确定这是处理东西的最佳方式(老实说,typeguards要求异步工作似乎有点可疑)。您可能试图强迫类型系统执行它不适合的操作


如果你的typeguard真的是
()=>真的
,你可以让它不
异步

错误消息解释了问题所在。这里有什么问题吗?您已经键入了作为布尔返回typeguard的函数。异步函数必须在typescript中返回一个
Promise
,因为不管您在function.emm中输入了什么代码,它们实际上都保证返回。我怎么能用Promise来实现呢?我不相信异步typeguards是typescript的一个功能。使您的typeguard同步,并让它接收所需的任何异步结果directly@CollinD谢谢,请不要在评论中回答,这样我就可以接受了。
async isSomethingAsyncPart(t: Something | OtherThing): IsSomethingAsyncResultSet {
  // do some await'ing here
  return asyncResults; 
}
isSomethingGuard(t: Something | OtherThing, asyncResults: IsSomethingAsyncResultSet): t is Something {
  // some synchronous evaluation using t and/or asyncResults
}

// kinda yucky but :shrug_emoji:
if (isSomethingGuard(t, await isSomethingAsyncPart(t)) { . . .}