"use strict"
import passport from "passport"
import { Strategy } from "passport-http-bearer"
passport.use(
"users",
new Strategy({ passReqToCallback: true }, (req, token, done) => {
if (token !== "foo") {
return done(null, false)
}
return done(null, {}, { scope: "user" })
})
)
[ts] src/authenticate.ts(8,46): error TS7006: Parameter 'req' implicitly has an 'any' type.
[ts] src/authenticate.ts(8,51): error TS7006: Parameter 'token' implicitly has an 'any' type.
[ts] src/authenticate.ts(8,58): error TS7006: Parameter 'done' implicitly has an 'any' type.
使用npm install @types/passport-http-bearer
安装的类型。
// Type definitions for passport-http-bearer 1.0.1
// Project: https://github.com/jaredhanson/passport-http-bearer
// Definitions by: Isman Usoh <https://github.com/isman-usoh>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="passport"/>
/// <reference types="express" />
import passport = require("passport");
import express = require("express");
interface IStrategyOptions {
scope?: string | Array<string>;
realm?: string;
passReqToCallback?: boolean;
}
interface IVerifyOptions {
message?: string;
scope: string | Array<string>;
}
interface VerifyFunction {
(token: string, done: (error: any, user?: any, options?: IVerifyOptions | string) => void): void;
}
interface VerifyFunctionWithRequest {
(req: express.Request, token: string, done: (error: any, user?: any, options?: IVerifyOptions | string) => void): void;
}
declare class Strategy implements passport.Strategy {
constructor(verify: VerifyFunction);
constructor(options: IStrategyOptions, verify: VerifyFunction);
constructor(options: IStrategyOptions, verify: VerifyFunctionWithRequest);
name: string;
authenticate(req: express.Request, options?: Object): void;
}
我的直觉是,没有使用 constructor(options: IStrategyOptions, verify: verifyFunctionWithRequest);
重载,因为我不知道它如何知道 passReqToCallback
是true
。这是类型定义的错误吗?
最佳答案
您关于过载导致问题的说法是正确的。我的猜测是,推理选择了第一个对参数的上下文类型有效的重载,但随后发现该函数有太多参数。重新排序参数也无法解决此问题,因为带有 VerifyFunction
的版本本身将变得无法访问。
不幸的是,解决方法并不好,您可以显式指定参数,也可以使用 Parameters
来避免键入所有参数:
passport.use(
"users",
new Strategy({ passReqToCallback: true }, (...[req, token, done]: Parameters<VerifyFunctionWithRequest>) => {
if (token !== "foo") {
return done(null, false)
}
return done(null, {}, { scope: "user" })
})
);
您还可以使用类型断言,但这可能会导致错误的返回值。
关于typescript - 如何解决 Passport-http-bearer TypeScript 重载类型问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62603379/