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?
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With