Morgan Fouque Morgan Fouque - 3 months ago 16
Javascript Question

Trouble converting JS to Typescript

Original JS code:

net.createServer(function (socket) {

// Identify this client
socket.name = socket.remoteAddress + ":" + socket.remotePort


My try of convertion:

class Peer {
public sock: net.Socket;
public name: string;
public pid: number;
constructor(sock:net.Socket,name:string)
{
sock = sock;
name = name;
}
}



// Load the TCP Library

var cid: number =0;
// Keep track of the chat clients
var clients: Peer[] = [];

// Start a TCP Server
net.createServer(function (socky: net.Socket) {
// Identify this client
var peer:Peer=new Peer(socky,"");
peer.name = peer.sock.remoteAddress + ":" + peer.sock.remotePort


First code runs smoothly without any problems, second output this:

C:\Users\Morgan\Desktop\typescript-starter\dist\app.js:21
peer.name = peer.sock.remoteAddress + ":" + peer.sock.remotePort;
^

TypeError: Cannot read property 'remoteAddress' of undefined
at Server.<anonymous> (C:\Users\Morgan\Desktop\typescript-starter\dist\app.j
s:21:21)
at emitOne (events.js:96:13)
at Server.emit (events.js:188:7)
at TCP.onconnection (net.js:1459:8)


And here is the translation from TS to JS of that piece of code:

var Peer = (function () {
function Peer(sock, name) {
sock = sock;
name = name;
}
return Peer;
}());
var cid = 0;
var clients = [];
net.createServer(function (socky) {
var peer = new Peer(socky, "");
peer.name = peer.sock.remoteAddress + ":" + peer.sock.remotePort;


Complete .TS file: http://pastebin.com/1UUtSzgz

Complete .JS file: http://pastebin.com/X5YAZjwu

Complete TS to JS converted file: http://pastebin.com/H25W7amh

I've tried setting accessors for the socket, it never worked.
if all the work is done on socky it works, but if i pass by peer, the undefined error pops.

Answer

Your Peer constructor isn't setting its instance members. It's setting the local parameters sock and name.

You probably meant to write something closer to this:

class Peer {
    public sock: net.Socket;
    public name: string;
    public pid: number;

    constructor(sock: net.Socket, name: string) {
        this.sock = sock;
        this.name = name;
    }
}

As a tip, TypeScript has a shorthand because this sort of code gets cumbersome to write.

class Peer {
    public pid: number;

    constructor(public sock: net.Socket, public name: string) {
    }
}

Notice the public modifier on each parameter. That automatically creates a public property for each parameter.