Import class in definition file (*d.ts)

后端 未结 4 1013
面向向阳花
面向向阳花 2020-11-28 21:03

I want to extend Express Session typings to allow use my custom data in session storage. I have an object req.session.user which is an instance of my class

4条回答
  •  北海茫月
    2020-11-28 22:04

    UPDATE

    Since typescript 2.9, you seem to be able to import types into global modules. See the accepted answer for more information.

    ORIGINAL ANSWER

    I think the problem you're facing is more about augmenting module declarations then class typing.

    The exporting is fine, as you'll notice if you try to compile this:

    // app.ts  
    import { User } from '../models/user'
    let theUser = new User('theLogin', 'thePassword')
    

    It seems like you are trying to augment the module declaration of Express, and you are really close. This should do the trick:

    // index.d.ts
    import { User } from "./models/user";
    declare module 'express' {
      interface Session {
        user: User;
        uuid: string;
      }
    }
    

    However, the correctness of this code depends of course on the original implementation of the express declaration file.

提交回复
热议问题