Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript创建带有错误的typeguard_Typescript_Typeguards - Fatal编程技术网

Typescript创建带有错误的typeguard

Typescript创建带有错误的typeguard,typescript,typeguards,Typescript,Typeguards,有什么方法可以帮助typescript推断正确的类型吗?也就是说,要知道如果中间件执行后的代码被“记录”了吗 基本上,目标是不必将authMiddleware(上下文)置于if检查中 看起来您需要类似于的东西,而不是TypeScript功能(从3.3开始)。您可能希望转到GitHub问题,并给它一个IfauthMiddleware是一个类型保护,为什么不执行If(authMiddleware(context)){const user=context.user}?@KarolMajewski首先想

有什么方法可以帮助typescript推断正确的类型吗?也就是说,要知道如果中间件执行后的代码被“记录”了吗


基本上,目标是不必将authMiddleware(上下文)置于if检查中

看起来您需要类似于的东西,而不是TypeScript功能(从3.3开始)。您可能希望转到GitHub问题,并给它一个If
authMiddleware
是一个类型保护,为什么不执行If(authMiddleware(context)){const user=context.user}?@KarolMajewski首先想到的是您通常不是只有一个中间件,而是至少有几个,这会创建多个嵌套的ifs,可读性不是很好。我相信随着发展的推进,可能还有其他好的理由
type LoggedContext = Required<ApolloContext>;
function authMiddleware(context: ApolloContext): context is LoggedContext {
  if (!context.user) {
    throw new AuthenticationError("Resolver requires login");
  }

  return true;
}
async user(_, { id }, context) {
    authMiddleware(context);

    const user = context.user;
    // expect typescript to infer that user is defined and not null
  },