我正在使用Flow构建一个nodeJS应用程序,我需要扩展快递$请求的默认快速注释,以适应我所连接的其他字段,如.user和.session。
不幸的是,当我尝试这样做并创建接受这种新请求类型的中间件时,流就会崩溃,我不知道我做错了什么。
流类型速递的原始代码是:
declare class express$Request extends http$IncomingMessage mixins express$RequestResponseBase {
....
}
declare type express$Middleware =
((req: express$Request, res: express$Response, next: express$NextFunction) => mixed) |
((error: ?Error, req: express$Request, res: express$Response, next: express$NextFunction) => mixed);所以我想我只需要扩展express$Request,然后我的所有中间件都应该使用新的属性,对吗?
declare class web$Request extends express$Request {
user: any,
isAuthenticated(): boolean,
session: {
loginForwardUrl: ?string,
},
}
const authenticationMiddleware: express$Middleware = (
req: web$Request, res, next
): mixed => {
if (req.isAuthenticated()) {
return next();
}
req.session.loginForwardUrl = req.originalUrl;
return res.redirect('/auth/login/google');
}不幸的是,这会产生超级复杂的错误:
function
This type is incompatible with
union: function type(s): web/src/index.js:113
Member 1:
function type: flow-typed/npm/express_v4.x.x.js:97
Error:
web$Request: web/src/index.js:114
This type is incompatible with the expected param type of
express$Request: flow-typed/npm/express_v4.x.x.js:97
Member 2:
function type: flow-typed/npm/express_v4.x.x.js:98
Error:
web$Request: web/src/index.js:114
This type is incompatible with an argument type of
null: flow-typed/npm/express_v4.x.x.js:98有人能解释一下这是怎么回事吗?怎么解决?
谢谢!
发布于 2017-09-28 21:53:41
错误表示,需要使用express$Request (成员1)或null (成员2)类型的参数/参数,但可以看到web$Request。
不幸的是,Flow不支持扩展/重写流/lib类型:
https://github.com/facebook/flow/issues/396
我开始做的是:
flow-typed install express@4.x.xexpress_v4.x.x.js从流类型/npm/移动到流类型/(外部流类型/npm/这样它就不会被未来的流类型安装覆盖,内部流类型/ so流将自动使declare blah语句成为全局的)declare class express$Request...下面(所以很容易找到,在declare module...内部使用它的位置),我说:
declare class express$Request extends express$Request { user: any; isAuthenticated(): boolean; session: { loginForwardUrl: ?string; }; }我这样做,而不是把我的自定义道具放在原来的类,以便很容易看出哪些道具是自定义的。
发布于 2020-12-01 10:17:53
如果您不喜欢修改原始的流类型/npm/express_v4.x.x.js,则可以使用flow 相交类型
import type {$Request} from 'express';
type MyType = {
foo: string
}:
export type CustomRequest = $Request & {
foo: MyType | void;
bar: string | void
};我喜欢这种方法,因为我可以将自己的类型定义添加到CustomRequest中。在类型化/npm/express_v4.x.x.js文件中扩展$Request时,这可能比较棘手。
https://stackoverflow.com/questions/44664555
复制相似问题