Alfons Ingomar Alfons Ingomar - 7 months ago 798
Javascript Question

Getting typescript to work for Angular 2 project with facebook login

I am trying to get up and running with Angular 2 and typescript. So far so good, but I am having some troubles to get a Facebook login message working. I found a project on github that demonstrated how this can be done. In this example, they have the following connector:

fbconnector.ts

export class FBConnector {

constructor(appID: string) {
if (!window.fbAsyncInit) {
console.log('define');
window.fbAsyncInit = function() {
FB.init({
appId: appID,
xfbml: true,
version: 'v2.5'
});
};
}
}

initFB() {
var js: any,
id = 'facebook-jssdk',
ref = document.getElementsByTagName('script')[0];

if (document.getElementById(id)) {
return;
}

js = document.createElement('script');
js.id = id;
js.async = true;
js.src = "//connect.facebook.net/en_US/sdk.js";

ref.parentNode.insertBefore(js, ref);
}

}


This gives the following 2 errors when I am compiling my typescript:

error TS2339: Property fbAsyncInit does not exist on type 'Window'.
error TS2304: Cannot find name 'FB'.


This makes sense when you think about it, typescript needs these variables defined. I guess this is partly because I am new to typescript, but I don't exactly know how this should be done. Should I make a custom typings file? Or should I use workarounds? (For example adding in front of window?)

Thanks in advance!

Answer

Eventually found the answer, DefinitelyTyped has type definitions for the Facebook Javascript SDK (over here).

All I had to do was add the file and reference to it with the following line at the top of my file:

/// <reference path="../../../typings/main/ambient/fbsdk/index.d.ts" />