[英]Augmenting external TypeScript modules
I'm currently studying how to augment external modules in TypeScript, reading the official docs and the DefinitelyTyped guides, checking examples and so on.我目前正在研究如何在 TypeScript 中增加外部模块,阅读官方文档和绝对类型指南,检查示例等。 My objective right now is to add custom properties to the express.Request
interface (eg a user
that implements a given User
interface.我的目标现在是添加到自定义属性express.Request
接口(例如一个user
实现给定User
界面。
Like the following:像下面这样:
// types/express/index.d.ts
declare namespace Express {
export interface Request {
user: types.User;
}
}
The User interface is declared in a separate declaration file:用户界面在单独的声明文件中声明:
// types/core.d.ts
declare namespace types {
interface User {
name: string;
}
}
The consuming code is a controller with two methods:消费代码是一个有两种方法的控制器:
// controller.ts
import { Request, Response, NextFunction } from "express";
const user = { name: "Hiago" };
class UserController {
getUser(req: Request, res: Response, next: NextFunction) {
req.user = user;
return next();
}
returnUser(req: Request, res: Response) {
const { user } = req;
return res.status(200).json(user);
}
}
This is working pretty fine.这工作得很好。 The problem is that since I have namespaces declarations only, I can't import these interfaces in my code.问题是因为我只有命名空间声明,所以我不能在我的代码中导入这些接口。 In the future I'd like to auto-generate interfaces like the User
shown above, and be able to use them in other parts of my app.将来我想像上面显示的User
一样自动生成界面,并且能够在我的应用程序的其他部分使用它们。
So I've found that declaring a module
, like the following, could help me achieve this:所以我发现声明一个module
,如下所示,可以帮助我实现这一目标:
// types/core.d.ts
declare module "core" {
export namespace types {
export interface User {
name: string;
}
}
}
Now I'm able to import the User
interface using import { types } from "core"
wherever I need to have it.现在我可以在需要的地方使用import { types } from "core"
导入User
界面。 But strangely, despite never complaining about anything on the types/express/index.d.ts
file, on my controller.ts
the compiler gives me a error TS2339: Property 'user' does not exist on type 'Request<ParamsDictionary>
.但奇怪的是,尽管从不抱怨types/express/index.d.ts
文件上的任何内容,但在我的controller.ts
,编译器给了我一个error TS2339: Property 'user' does not exist on type 'Request<ParamsDictionary>
。
I've put all the code in this repo , so that anybody willing to help can reproduce this error.我已将所有代码放在此repo 中,以便任何愿意提供帮助的人都可以重现此错误。
Change your // types/express/index.d.ts to:将您的 // types/express/index.d.ts 更改为:
import { types } from "core";
declare module 'express' {
interface Request {
user: types.User;
}
}
In your controller.ts you are using the type from module express, not namespace.在您的 controller.ts 中,您使用的是来自模块 express 的类型,而不是命名空间。 (in some cases they just reexport it, but it seems express is not the case). (在某些情况下,他们只是将其重新出口,但似乎快递并非如此)。 With this change it should work.通过此更改,它应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.