Node.js TypeScript |名称空间';global.Express';没有导出的成员';ICustomRequest';
我正在将现有项目迁移到它。我创建了一个名为yelp-camp.d.ts的文件:Node.js TypeScript |名称空间';global.Express';没有导出的成员';ICustomRequest';,node.js,typescript,express,Node.js,Typescript,Express,我正在将现有项目迁移到它。我创建了一个名为yelp-camp.d.ts的文件: declare namespace NodeJS { export interface ProcessEnv { MONGO_URI: string; GOOGLE_API: string; SECRET_KEY: string; } } declare namespace Express { export interface ICustomRequestUser extends
declare namespace NodeJS {
export interface ProcessEnv {
MONGO_URI: string;
GOOGLE_API: string;
SECRET_KEY: string;
}
}
declare namespace Express {
export interface ICustomRequestUser extends Express.User{
_id: string;
username: string;
isAdmin: boolean;
}
export interface ICustomRequest<T> extends Express.Request {
body: T;
params: {
id: string;
comment_id: string;
};
}
}
声明命名空间节点{
导出接口ProcessEnv{
MONGO_URI:string;
GOOGLE_API:string;
密钥:字符串;
}
}
声明命名空间表达式{
导出接口ICustomRequestUser扩展了Express.User{
_id:字符串;
用户名:字符串;
isAdmin:布尔型;
}
导出接口ICustomRequest扩展了Express.Request{
身体:T;
参数:{
id:字符串;
注释_id:string;
};
}
}
在我的控制器上,我使用这个ICustomRequest接口,如下所示:
async create(req: Express.ICustomRequest<ICampground>, res: Response) {
try {
const data = await this.geocoder.geocode(req.body.location);
const imageUrl = await upload(req.file);
const newCampground = {
name: req.body.name,
image: imageUrl,
description: req.body.description,
author: {
id: req.user!._id,
username: req.user!.username,
},
price: req.body.price,
location: data[0].formattedAddress!,
lat: data[0].latitude!,
lng: data[0].longitude!,
};
await CampgroundModel.create(newCampground);
return res.status(201).json(newCampground);
} catch (err) {
console.log(err.message);
return res.status(401).json({});
}
}
异步创建(req:Express.ICustomRequest,res:Response){
试一试{
const data=wait this.geocoder.geocode(req.body.location);
const imageUrl=等待上传(请求文件);
康斯特新营地={
名称:req.body.name,
图片:imageUrl,
描述:req.body.description,
作者:{
id:REQUE.user!。\u id,
用户名:req.user!.username,
},
价格:需求主体价格,
位置:数据[0]。formattedAddress!,
纬度:数据[0]。纬度!,
lng:数据[0]。经度!,
};
等待营地模型。创建(新营地);
返回res.status(201.json)(新营地);
}捕捉(错误){
控制台日志(错误消息);
返回res.status(401).json({});
}
}
但是我得到了这个错误:命名空间“global.Express”没有导出成员“ICustomRequest”。我怎么才能解决这个问题呢?我感觉你遗漏了什么(也许你在
yelp camp.d.ts
中有一个import
)。然而,你所做的毫无意义,是一种糟糕的做法。如果您正在定义类型以注释自己的应用程序,请不要尝试将它们添加到现有库的声明中。my yelp camp.d.ts上没有导入。。。在这种情况下,最好的做法是什么?这只是一个猜测,因为存在一个常见的范围界定错误。无论如何,ICustomRequest
是您的类型。不要将它添加到Express
全局名称空间-直接使用它。但是我需要扩展请求,所以这是正常的,对吗?没有实现名称空间。我试图创建我的名称空间并扩展Express.User和Express.Request,但给出了相同的错误。好吧,这很有效!非常感谢。我感觉你遗漏了什么(也许你在yelp camp.d.ts
中有一个import
)。然而,你所做的毫无意义,是一种糟糕的做法。如果您正在定义类型以注释自己的应用程序,请不要尝试将它们添加到现有库的声明中。my yelp camp.d.ts上没有导入。。。在这种情况下,最好的做法是什么?这只是一个猜测,因为存在一个常见的范围界定错误。无论如何,ICustomRequest
是您的类型。不要将它添加到Express
全局名称空间-直接使用它。但是我需要扩展请求,所以这是正常的,对吗?没有实现名称空间。我试图创建我的名称空间并扩展Express.User和Express.Request,但给出了相同的错误。好吧,这很有效!非常感谢。