Morgan Fouque Morgan Fouque - 1 year ago 131
Javascript Question

Trouble converting JS to Typescript

Original JS code:

net.createServer(function (socket) {

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

My try of convertion:

class Peer {
public sock: net.Socket;
public name: string;
public pid: number;
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.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.sock.remoteAddress + ":" + peer.sock.remotePort;

TypeError: Cannot read property 'remoteAddress' of undefined
at Server.<anonymous> (C:\Users\Morgan\Desktop\typescript-starter\dist\app.j
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.sock.remoteAddress + ":" + peer.sock.remotePort;

Complete .TS file:

Complete .JS file:

Complete TS to JS converted file:

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 Source

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; = 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download