我通过向节点/快速项目添加类型来进行一些操作。
我正在使用TypeScript 2.2并表达4.x和我通过npm安装的类型:
npm install --save-dev @types/express
import * as express from "express"
const app: express.Application = express()
app.get("/hello", (req, res) => {
res.send("world")
})
这给了我:
src/app.ts(33,22): error TS7006: Parameter 'req' implicitly has an 'any' type.
src/app.ts(33,27): error TS7006: Parameter 'res' implicitly has an 'any' type.
我试图避免为所有请求处理程序执行此操作:
(req: express.Request, res: express.Response) => {}
在我看来,它应该能够推断出那些。我错了吗?这不可能吗?
tsconfig.json:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"noImplicitAny": true,
"sourceMap": true,
"outDir": "dist",
"typeRoots": ["src/types", "node_modules/@types"]
},
"include": [
"src/**/*.ts"
]
}
谢谢!
答案 0 :(得分:1)
快递库的get方法过载(请参阅此处演示https://github.com/DefinitelyTyped/DefinitelyTyped/blob/14cfa9f41c2835fcd22e7243a32b25253c310dee/express-serve-static-core/index.d.ts#L25-L40)
interface RequestHandler {
(req: Request, res: Response, next: NextFunction): any;
}
interface ErrorRequestHandler {
(err: any, req: Request, res: Response, next: NextFunction): any;
}
type PathParams = string | RegExp | (string | RegExp)[];
type RequestHandlerParams = RequestHandler | ErrorRequestHandler | (RequestHandler | ErrorRequestHandler)[];
interface IRouterMatcher<T> {
(path: PathParams, ...handlers: RequestHandler[]): T;
(path: PathParams, ...handlers: RequestHandlerParams[]): T;
}
RequestHandlerParams
使得无法可靠地确定req
和res
的内容。建议:暂时注释它