打字稿:如何使用功能缩小私有成员类型?
Let's assume I've got the following disposable class:
class Data {
private buffer?: ArrayBuffer;
constructor(buffer: ArrayBuffer) {
this.buffer = buffer;
}
get data(): ArrayBuffer {
this.assertNotDisposed();
return this.buffer;
}
dispose(): void {
this.assertNotDisposed();
delete (this as Data).buffer;
}
private assertNotDisposed(): asserts this is this &
Required<Pick<Data, 'buffer'>> {
if (this.buffer === undefined) {
throw new Error('instance is disposed');
}
}
}
20NQKQ6XHWYGA7TA8ZSAKLSRRKEG46RGCTAUJNWP7EREG6RZVZXXXAA “ 。此方法还缩小了此
的类型,因此 this.buffer 不再是可选的,如果实例未处理。
可悲的是,以上代码无法正常工作,因为成员buffer
是private
,因此pick&lt; data,'buffer'&gt;
使用类型'“缓冲区”'失败不满足约束'键数据'
,因为data
仅反映public> public
接口。
在保留私人缓冲区
的同时,有没有办法使其以类型的安全方式工作?
Let's assume I've got the following disposable class:
class Data {
private buffer?: ArrayBuffer;
constructor(buffer: ArrayBuffer) {
this.buffer = buffer;
}
get data(): ArrayBuffer {
this.assertNotDisposed();
return this.buffer;
}
dispose(): void {
this.assertNotDisposed();
delete (this as Data).buffer;
}
private assertNotDisposed(): asserts this is this &
Required<Pick<Data, 'buffer'>> {
if (this.buffer === undefined) {
throw new Error('instance is disposed');
}
}
}
As you can see, it uses the method assertNotDisposed
to ensure the methods can only be called as long as the instance has not been disposed. This method also narrows the type of this
, so this.buffer
is not optional anymore, if the instance is not disposed.
Sadly, the above code doesn't work like that, because the member buffer
is private
and therefore Pick<Data, 'buffer'>
fails with Type '"buffer"' does not satisfy the constraint 'keyof Data'
, as Data
only reflects the public
interface.
Is there a way to get this to work in a type-safe way while keeping private buffer
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论