jan*_*neh 5 node.js express typescript
我在为节点/快递项目添加类型方面有点蠢蠢欲动.
我正在使用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")
})
Run Code Online (Sandbox Code Playgroud)
这给了我:
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.
Run Code Online (Sandbox Code Playgroud)
我试图避免为所有请求处理程序执行此操作:
(req: express.Request, res: express.Response) => {}
Run Code Online (Sandbox Code Playgroud)
在我看来它应该能够推断出那些.我错了吗?这不可能吗?
tsconfig.json:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"noImplicitAny": true,
"sourceMap": true,
"outDir": "dist",
"typeRoots": ["src/types", "node_modules/@types"]
},
"include": [
"src/**/*.ts"
]
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
尝试添加Express类型
import {Express} from 'express'
var express = require('express')
const app:Express = express();
app.get('/test', (req, res) => {
res.send({ message: 'Welcome to Express!' });
});
Run Code Online (Sandbox Code Playgroud)
Express库的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;
}
Run Code Online (Sandbox Code Playgroud)
这RequestHandlerParams使得我们无法可靠地确定什么req和res拥有什么。建议:暂时注释一下