为什么出现的属性"用户"在类型"请求<参数字典,任何,任何,查询>"上不存在



运行ts节点时出现以下错误。

我将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
};

我错过了什么?

问题是ts-node没有选择你的类型扩展,但tsc能够。相关的GitHub问题有更多细节,但TL;DR是指您必须将自定义类型放在node_modules/@types之前,即:

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

paths也是不需要的,所以您可能可以删除它(无论如何都是错误的(。

{
"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-baabed09472

相关内容

  • 没有找到相关文章

最新更新