Search code examples
javascriptangulartypescriptdeclaremixpanel

declare javascript methods in Angular 2 / typescript to avoid propery x does not exist errors


I use some JavaScript in my Angular 2, TypeScript project. For example I use MixPanel that have a javascript file and some methods that look like this:

mixpanel.people.set({
    "$first_name": "Joe",
    "$last_name": "Doe",
    "$created": "2013-04-01T09:02:00",
    "$email": "joe.doe@example.com"
});

and this:

   mixpanel.track("Video played", {
        "Video length": 213,
        "id": "hY7gQr0"
    });

Calling this methods work, but typescript can not find any definitions of this mixpanel object so it throws errors. This is problematic because I can't compile with these errors...

Therefore, I am using this little hack to declare mixpanel like this:

import { Injectable } from '@angular/core';

declare var mixpanel: {
  track(event: string, data: any): void;
  identify(data: any): void;
  people(data: any): void;
  track_links(domQuery: string, eventName: string, properties: any): void;
};

@Injectable()
export class MixPanelService {

  constructor() { }

  public track(event: string, data: any) {
    mixpanel.track(event, data);
  }

  public track_links(domQuery: string, eventName: string, properties: any) {
    mixpanel.track_links(domQuery, eventName, properties);
  }

  public identify(id: string) {

    mixpanel.people.set({ <---- ERROR: Property 'set' does not exist on type '(data: any) => void'.at line 37 col 21
      '$first_name': id
    });
    mixpanel.identify(id);

  }
}

I am declaring mixpanel.people, but not mixpanel.people.set. This causes an error.

Anyone know how I should declare mixpanel var to fix this? Or if there is a better solution?


Solution

  • declare var mixpanel:any; 
    

    can solve your all problems;