8

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?

Eldon Lesley
  • 915
  • 6
  • 19
  • 38

3 Answers3

7

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.

Glen Hughes
  • 4,712
  • 2
  • 20
  • 25
1

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');
Fenton
  • 241,084
  • 71
  • 387
  • 401
  • Nope, The error still there, and I checkedthe lib.d.ts and there's no MozWebSocket – Eldon Lesley Oct 25 '12 at 13:12
  • and also, if I declare the interface fully with the websocket, I don't get any error of duplicate declarations – Eldon Lesley Oct 26 '12 at 07:11
  • the other code is just simple code as prompt and string format, but the error is only in the window.WebSocket, it will be alright if maybe there's a way in vs2012 to turn off the exceptions from being thrown – Eldon Lesley Oct 26 '12 at 13:06
  • Steve, could you please elaborate a bit on the `declare interface` syntax. If I add your code snippet to my .ts file I get an error saying that the declare keyword "can not appear on an interface declaration". Indeed "declare interface" do not appear at all in the lib.d.ts file or the TypeScript language specification. Oh and one more thing, why do you type the WebSocket and MozWebSocket to any, why not type them to WebSocket? – Martin Andersson Sep 05 '13 at 08:00
  • I have updated the answer to match the language and lib.d.ts from TypeScript 0.9.1.1 – Fenton Sep 05 '13 at 10:56
0

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