我需要访问writable.write函数中的一些类实例数据。下面是一段简短的类型记录代码,说明了我想要做的事情:
import * as socketio from 'socket.io'
import { Writable } from 'stream'
export class DataClient {
public socket: socketio.Socket
private writable: Writable
constructor(socket: socketio.Socket) {
this.socket = socket
this.writable = new Writable({
write: function (chunk, encoding, next) {
this.socket.emit('data', chunk)
next()
}.bind(this),
})
}
}我从ESLint得到以下错误:
any
'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)
dataClient.ts(12, 14): An outer value of 'this' is shadowed by this container.我尝试过使用<>和as进行转换,但这并没有什么不同。实际的代码更复杂,但这在最简单的情况下显示了问题。此外,虽然我可能只能引用套接字(参数),但我还需要访问其他实例数据项,它们不是构造函数的参数。
有没有办法让TS知道"this“指的是DataClient实例?
发布于 2022-05-24 19:08:50
您应该使用一个箭头函数来表示写方法,然后这将引用DataClient实例:
import * as socketio from "socket.io";
import { Writable } from "stream";
export class DataClient {
public socket: socketio.Socket;
private writable: Writable;
constructor(socket: socketio.Socket) {
this.socket = socket;
this.writable = new Writable({
write: (chunk, encoding, next) => {
this.socket.emit("data", chunk);
next();
},
});
}
}另一种解决方案是将函数指定为类的方法:
import * as socketio from "socket.io";
import { Writable } from "stream";
export class DataClient {
public socket: socketio.Socket;
private writable: Writable;
constructor(socket: socketio.Socket) {
this.socket = socket;
this.writable = new Writable({
write: this.writeFunc,
});
}
writeFunc(chunk: any, encoding: BufferEncoding, next: any): void {
this.socket.emit("data", chunk);
next();
}
}https://stackoverflow.com/questions/72368044
复制相似问题