打字稿2.2 Express req,res含义任意

时间:2017-03-02 16:01:01

标签: 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")
})

这给了我:

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"
  ]
}

谢谢!

1 个答案:

答案 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使得无法可靠地确定reqres的内容。建议:暂时注释它