如何覆盖外部TypeScript接口

我在TypeScript项目中使用passportThe 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 User {
    id: number
    username: string,profilePicture: string,name: string
}

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

是否可以在src文件夹中写入覆盖Express.User的定义文件?我尝试将定义文件复制并修改到我的src目录中,但显示为

Augmentations for the global scope can only be directly nested in external modules or ambient module declarations

没有declare global的tsc仍将req.user视为一个空接口。

我必须在tsconfig.json中包含什么配置才能使用此替代?

chenxiangxie0 回答:如何覆盖外部TypeScript接口

同一作用域中的接口声明被合并。也就是说,以下

interface A {
  name: string;
}

interface A {
  id: number;
}

声明一个具有两个属性Aname的单一接口id

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

declare global {
  namespace Express {
    interface User {
      id: number,username: string,profilePicture: string,name: string
    }
  }
}
本文链接:https://www.f2er.com/3129559.html

大家都在问