Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript with WebSocket

I have a webapp with JavaScript and websocket applied inside the webapp,

Now, I wanted to try to move my webapp to typescript which is type safe,

The problem is, when I declare and initialize the websocket, the typescript (in visual studio 2012) generating an error: "The property 'WebSocket' does not exist on value of type 'Window'"

But in the JavaScript, the websocket is running and no error,

This is the code:

var Socket = window.WebSocket || window.MozWebSocket;

in JavaScript it's alright, but in the typescript it genereated the error,

How can I solve this? Or is there a way in Visual Studio 2012 to ignore the error so the typescript can be built?

like image 473
Eldon Lesley Avatar asked Oct 25 '12 12:10

Eldon Lesley


2 Answers

Try accessing the properties like this:

var Socket = window['WebSocket'] || window['MozWebSocket'];

Using a string indexer gets around the compile time validations and allows for dynamic operations.

like image 153
Glen Hughes Avatar answered Nov 13 '22 08:11

Glen Hughes


I have updated my answer to keep up with changes in newer versions of TypeScript...

If the MozWebSocket is identical to WebSocket - you can solve the issue this way:

declare var MozWebSocket: {
    prototype: WebSocket;
    new (url: string): WebSocket;
    new (url: string, prototcol: string): WebSocket;
    new (url: string, prototcol: string[]): WebSocket;
    OPEN: number;
    CLOSING: number;
    CONNECTING: number;
    CLOSED: number;
}

var Socket: typeof WebSocket = WebSocket || MozWebSocket;

var socket = new WebSocket('url');
like image 44
Fenton Avatar answered Nov 13 '22 07:11

Fenton