【发布时间】: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