为什么“请求<ParamsDictionary,任何,任何查询>”类型上不存在“被占用的属性”用户

时间:2020-05-02 17:47:01

标签: node.js typescript ts-node

运行ts-node时出现以下错误。

我如下定义d.ts以使用“ req.user”并应用了tsconfig.json。

Path: src/@types/express/index.d.ts

import { User } from '../../model/user/user.interface';

declare global {
    namespace Express {
        interface Request {
            user?: User['employeeId'];
        }
    }
}

tsconfig.json

{
    "compilerOptions": {
        "typeRoots": [
          "./node_modules/@types",
          "./src/@types"
        ],
        "rootDir": ".",
        "module": "CommonJS",
        "strict": true,
        "outDir": "dist",
        "baseUrl": "./src",
        "paths": {
            "*": ["node_modules/@types/*", "src/@types"]
        },
        "esModuleInterop": true
    },
    "include": ["src/**/*.ts"]
}

控制器

Path: src/api/posts/controller.ts

export const get = (req: Request, res: Response) => {
  ...
  const { user } = req;
  -> occrud Error
};

我想念什么?

2 个答案:

答案 0 :(得分:1)

问题在于ts-node不能使用您的类型扩展名,但是tsc可以。相关的GitHub Issue有更多详细信息,但TL; DR是您必须将客户类型放在node_modules/@types之前,即:

"typeRoots": [
  "./src/@types",
  "./node_modules/@types"
]

paths也不是必需的,因此您可以将其删除(无论如何是错误的)。

答案 1 :(得分:0)

{
    "compilerOptions": {
        "rootDir": "./src",
        "module": "CommonJS",
        "strict": true,
        "outDir": "./dist",
        "baseUrl": "./node_modules",
        "paths": {
            "*": ["./@types/*","./*", "../src/@types"]
        },
        "esModuleInterop": false,
        "types": ["node", "express"]
    },
    "include": ["src/**/*.ts"]
}

让我们的npm -D install @types/node @types/express

现在让我们创建一个类控制器

import { Request, Response, NextFunction } from "express";


export type EndPointResponse = Promise<Response>;
export class ListController {

    public constructor () {
        this.getAll = this.getAll.bind(this);
        this.getById = this.getById.bind(this);
    }

    public async getAll (req: Request, res: Response, next: NextFunction): EndPointResponse {

    }
    public async getById (req: Request, res: Response, next: NextFunction): EndPointResponse {

}

这里您有完整的说明https://medium.com/@enetoOlveda/use-sequelize-and-typescript-like-a-pro-with-out-the-legacy-decorators-fbaabed09472