meteortypescript

How to override user.profile type?


In meteor-typescript's definition file, the user.profile object is typed as any.

What's the Typescript way to extend the user object and change the profile type?

I tried

interface IMyUserProfile {
  foo: boolean;
}

namespace Meteor {
  export interface User: {
    profile: IMyUserProfile
  }
}

But TS just says "duplicate identifier".

I know I could change it in the definitions file directly but for obvious reasons I'd prefer not to do that.


Solution

  • Typescript supports declaration merging but that would have worked if you'd add a property that isn't already in place, for example:

    namespace Meteor {
        export interface User {
            newPropertry: any;
        }
    }
    

    But since the User interface already has profile the compiler complains about it.

    What you can do is:

    namespace Meteor {
        export interface MyUser extends User {
            profile: IMyUserProfile;
        }
    }
    

    And then just cast the user instance you have to Meteor.MyUser.
    You can of course remove that from the Meteor namespace:

    export interface MyUser extends Meteor.User {
        profile: IMyUserProfile;
    }