运行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
};
我想念什么?
答案 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 {
}