gpt4 book ai didi

typescript - 如何覆盖外部 TypeScript 接口(interface)

转载 作者:行者123 更新时间:2023-12-05 00:58:01 25 4
gpt4 key购买 nike

我正在使用 passport在 TypeScript 项目中。 The DefinitelyTyped type definition for passport覆盖 Express 请求以包含 user 属性。但是它将用户定义为一个空界面:

index.d.ts

declare global {
namespace Express {
...
// tslint:disable-next-line:no-empty-interface
interface User {}

interface Request {
...
user?: User;
...
}
}
}

但是,在我的整个应用程序中,我希望 req.user 成为这种类型的接口(interface):

interface User {
id: number
username: string,
profilePicture: string,
name: string
}

我厌倦了将 req.user 写成 User | null 在我的整个应用程序中。我可以直接覆盖定义文件中的接口(interface)定义,但修改 node_modules 中的文件似乎是不好的做法,如果我更新类型模块,可能会被覆盖。

有没有办法在我的 src 文件夹中编写一个覆盖 Express.User 的定义文件?我试过自己将定义文件复制并修改到我的 src 目录,但它说

全局范围的增强只能直接嵌套在外部模块或环境模块声明中

没有 declare global tsc 仍然将 req.user 视为一个空接口(interface)。

我必须在 tsconfig.json 中包含什么配置才能获取此覆盖?

最佳答案

合并同一范围内的接口(interface)声明。也就是说,下面的

interface A {
name: string;
}

interface A {
id: number;
}

声明一个接口(interface),即A,具有两个属性,nameid

因此,只需使用与护照相同的技术来调整类型

// ensure file is parsed as a module
export {}

declare global {
namespace Express {
interface User {
id: number,
username: string,
profilePicture: string,
name: string
}
}
}

关于typescript - 如何覆盖外部 TypeScript 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58787934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com