gpt4 book ai didi

javascript - 无法将 JS 转换为 Typescript

转载 作者:行者123 更新时间:2023-11-30 15:51:53 25 4
gpt4 key购买 nike

原始JS代码:

net.createServer(function (socket) {

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

我的转换尝试:

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

第一个代码运行顺利,没有任何问题,第二个输出:

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)

这是这段代码从 TS 到 JS 的翻译:

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;

完整的 .TS 文件:http://pastebin.com/1UUtSzgz

完整的 .JS 文件:http://pastebin.com/X5YAZjwu

完整的TS转JS文件:http://pastebin.com/H25W7amh

我试过为套接字设置访问器,但从未奏效。如果所有工作都是在 socky 上完成的,它就可以工作,但如果我经过同行,就会弹出未定义的错误。

最佳答案

您的Peer 构造函数未设置其实例 成员。它正在设置本地参数 sockname

你可能打算写一些更接近于此的东西:

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

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

作为提示,TypeScript 有一个简写形式,因为这种代码写起来很麻烦。

class Peer {
public pid: number;

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

注意每个参数上的 public 修饰符。这会自动为每个参数创建一个公共(public)属性。

关于javascript - 无法将 JS 转换为 Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39197442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com