【问题标题】:Typescript create typeguard with errors打字稿创建带有错误的类型保护
【发布时间】:2019-02-23 21:59:18
【问题描述】:
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
  },

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

基本上,目标是不必将 authMiddleware(context) 放入 if 检查中。

【问题讨论】:

  • 如果authMiddleware 是类型保护,为什么不使用if (authMiddleware(context)) { const user = context.user }?
  • @KarolMajewski 首先想到的是您通常不会只有一个中间件,而是至少有几个,这会创建多个嵌套的 if 并且可读性不是很好。我敢肯定,随着发展的深入,可能还有其他充分的理由

标签: typescript typeguards


【解决方案1】:

看起来您想要type assertion at block-scope level 之类的东西,这不是 TypeScript 功能(从 3.3 开始)。如果它特别引人注目并且尚未被提及,您可能想去那个 GitHub 问题并给它一个 ? 或描述您的用例。因此,目前没有办法在不进行if 检查的情况下使用类型保护明确地缩小变量的类型。

你能做些什么呢?在这种情况下,我通常做的是将类型保护替换为返回缩小对象的函数,因此不要返回 x is T,而是返回 T:

function authMiddleware(context: ApolloContext): LoggedContext {
  if (!context.user) {
    throw new AuthenticationError("Resolver requires login");
  }
  // the following assertion is equivalent to the type guard returning true
  return context as LoggedContext;
}

现在当你使用这个函数时,所有后续引用都使用返回值而不是原始参数:

const aContext = authMiddleware(context);
// use aContext instead of context from now on:

const user = aContext.user; // string

也许这会对您有所帮助,或为您提供一些关于如何继续进行的想法。祝你好运!

【讨论】:

    猜你喜欢
    • 2021-03-25
    • 1970-01-01
    • 2017-05-18
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 2020-05-11
    • 1970-01-01
    相关资源
    最近更新 更多