TypeScript - 使用 HOC 验证对象属性



我有一个上下文接口,如下所示:

export interface IReq extends Request {
user?: IUser;
}
export interface IContext {
req: IReq;
res: Response;
}

我有一个经过身份验证的 HOC 来包装左轮手枪:

import { IContext } from "generic";
export default (next: Function) => <R, A, I>(root: R, args: A, context: IContext, info: I) => {
if (!context.req.user) {
throw new Error(`Unauthenticated!`);
}
return next(root, args, context, info);
};

该函数检查以确保用户可用,如果不可用,它将引发错误。

当我将解析器包装在 HOC 中时,TypeScript 仍然抱怨 context.req.user 可能未定义。

import isAuthenticated from '../../utils/isAuthenticated';
export default {
Add: isAuthenticated((
_: null,
{ input }: { input: AddInput },
context: IContext
) => {
return Controller.add({ ...input }, context.req.user);
})
};

context.req.user 不能取消定义,因为 isAuthenticated HOC 甚至在调用子函数之前都会抛出错误。

有没有更好的方法来构建它?

打字稿编译器只能这么聪明。

如果你超级确定由于你自己的应用程序逻辑,这个值不能nullundefined,那么你可以通过在表达式的末尾添加一个!来告诉 Typescript。

人为的例子:

let foo: string | null = null
function setFoo() { foo = 'a,b,c' }
setFoo()
console.log(foo!.split(','))
//             ^ here

或者在您的情况下:

context.req.user!

但要谨慎使用它,因为如果你错了,并且那里可能有一个空值,你可能会抛出一个异常。

最新更新