打字稿:如何使用功能缩小私有成员类型?

发布于 2025-01-30 16:30:06 字数 975 浏览 2 评论 0原文

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 不再是可选的,如果实例未处理。

可悲的是,以上代码无法正常工作,因为成员bufferprivate,因此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');
    }
  }
}

Link to playground

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文