Eldon Lesley
Eldon Lesley

Reputation: 935

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?

Upvotes: 8

Views: 10950

Answers (3)

Fenton
Fenton

Reputation: 251262

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

Upvotes: 1

Martin Duparc
Martin Duparc

Reputation: 21

You can extend the window definition (call it "window.extend.d.ts"):

interface Window {
     WebSocket: any;
     MozWebSocket: any;
}

Works with TypeScript 0.8.3.0

Upvotes: 0

Glen Hughes
Glen Hughes

Reputation: 4832

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.

Upvotes: 7

Related Questions