如何在 writeitable.write 函数中使用内部的"this"



我需要访问一些类实例数据在一个可写的。写函数。下面是一个简短的typescript代码片段,它说明了我要做的事情:

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实例?

您应该使用箭头函数来表示写入方法,那么这将引用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();
}
}

最新更新