2016-10-25 37 views
0

我在Angular 2的TypeScript項目中使用了一些JavaScript。 例如筆者使用的MixPanel有一個JavaScript文件和一些方法是這樣的:在Angular 2/typescript中聲明javascript方法以避免propery x不存在錯誤

mixpanel.people.set({ 
    "$first_name": "Joe", 
    "$last_name": "Doe", 
    "$created": "2013-04-01T09:02:00", 
    "$email": "[email protected]" 
}); 

這:

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

調用此方法的工作,但打字稿找不到這個任何定義混合面板對象,所以它會引發錯誤。這是有問題的,因爲我不能用這些錯誤編譯...

因此,我使用的這個小黑客類似這樣的聲明mixpanel:

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); 

    } 
} 

我聲明mixpanel.people,但不是mixpanel.people.set。 這會導致錯誤。

任何人都知道我應該如何聲明mixpanel var來解決這個問題?或者如果有更好的解決方案?

+0

它可能,我相信看defs。你能把錯誤放在這裏嗎? – Gary

回答

3
declare var mixpanel:any; 

可以解決你所有的問題;

1

做一個自己的類MixPanel,如:

export class MixPanel 
{ 
    track(event: string, data: any): void 
    { 
    } 

    identify(data: any): void 
    { 
    } 
    ... 
}