类型 'Request<ParamsDictionary>' 上不存在属性



当试图从包express扩展Request接口以添加一些自定义属性时,我收到以下typescript错误:

TS2339: Property '' does not exist on type 'Request<ParamsDictionary>'.

你知道怎么解决吗?

由于最近更新了它的类型和依赖项,我发现以下内容应该可以修复应用程序中的错误。

在您的tsconfig.json

{
"compilerOptions": {
//...
"typeRoots": [
"./custom_typings",
"./node_modules/@types"
],
}
// ...
}

在你的自定义打字机

// custom_typings/express/index.d.ts
declare namespace Express {
interface Request {
customProperties: string[];
}
}

我最近遇到了同样的问题,我遵循了之前评论中的解决方案,这次回购和我仍然有同样的问题。在做了更多的挖掘之后,它似乎是ts节点的一个bug。

要解决这个问题,您需要使用--files标志运行服务器

因此,如果您正常运行服务器ts-node ./src/server.tsnodemon ./src/server.ts将其更改为ts-node --files ./src/server.tsnodemon --files ./src/server.ts

在那之后,我能够在启动服务器时消除VScode错误和错误。

只需添加以下内容,它只需向快速请求接口添加一个自定义属性

declare global {
namespace Express {
interface Request {
propertyName: string; //or can be anythin
}
}
}

在我的例子中,它缺少express的类型。我目前正在做的是将我们的代码库从Yarn迁移到PNPM。PNPM的不同之处在于,它没有像Yarn那样提升依赖关系,所以我不得不在package.json上为每个使用该依赖关系的工作区添加依赖关系。

这是我遇到的错误:

TSError: ⨯ Unable to compile TypeScript:
../server/src/api/filters/googleFilter.ts:6:23 - error TS2339: Property 'headers' does not exist on type 'Request<core.ParamsDictionary>'.
6   const idToken = req.headers.authorization;

当我决定打开该工作区的node_modules文件夹时,我花了好几次搜索才找到修复程序。node_modules/@types/express/index.d.ts内部

/// <reference types="express-serve-static-core" />
/// <reference types="serve-static" />
import * as bodyParser from "body-parser";
import serveStatic = require("serve-static");
import * as core from "express-serve-static-core";
import * as qs from "qs";

我看到我的IDE显示错误,告诉我它找不到express-serve-static-coreserve-static的类型,所以我所做的是将其添加到该工作区的package.json上,并修复了终端上的错误。

希望这能帮助其他人谁会遇到同样的问题与PNPM。

这对我很管用

使用ts-node

按照@Rishav Sinha 的建议,添加以下文件以将属性添加到express Request接口

  1. 添加此文件src/types/types.custom.d.ts
declare global {
declare namespace Express {
interface Request {
user?: any,
page?: number,
}
}
}
// If this file has no import/export statements (i.e. is a script)
// convert it into a module by adding an empty export statement.
export { }
  1. 添加到tsconfig.json
{
"compilerOptions": {
//...
"typeRoots": [
"./types",
"./node_modules/@types"
],
}
// ...
}
  1. 使用@Shahar Sharron建议的--files选项运行此命令

如果您在全球范围内安装了ts-node

$ ts-node --files ./src/index.ts

或从您的项目依赖ts-node运行

$ npx ts-node --files ./src/index.ts

使用nodemon

如果您想使用nodemom

  1. 将此文件添加到文件夹项目nodemon.json
{
"watch": ["src/**/*.ts"],
"ext": "ts,json",
"ignore": [
"src/**/*.spec.ts",
"src/**/*.test.ts"
],
"exec": "npx ts-node --files ./src/index.ts"
}
  1. 运行nodemon
$ nodemon

最新更新