首页 > 解决方案 > 在 TypeScript 中,为什么 Symbols for Privacy 会向消费者抛出错误?

问题描述

我希望我的一些类字段和方法有一些隐私

在我的项目中,我创建了一些使用符号来访问私有成员的类

模式基本上是:

const _counter = Symbol()

export class CountingThing {
  private [_counter] = 0
}

我认为这是实现隐私的好方法,直到 typescript 最终包含#私有字段语法——这对于仅使用 javascript 的 npm 消费者来说非常有效

不幸的是,这种模式似乎不适用于我的包的打字稿消费者

我的消费者项目在打字稿编译期间出现这些错误:

node_modules/quizzly/dist/components/quizzly-question.d.ts:8:13 - error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type.

8     private [_getChoices];
              ~~~~~~~~~~~~~

node_modules/quizzly/dist/components/quizzly-question.d.ts:8:14 - error TS2304: Cannot find name '_getChoices'.

8     private [_getChoices];
              ~~~~~~~~~~~

node_modules/quizzly/dist/components/quizzly-quiz.d.ts:26:13 - error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type.

26     private [_getSlottedElements];
              ~~~~~~~~~~~~~~~~~~~~~

node_modules/quizzly/dist/components/quizzly-quiz.d.ts:26:14 - error TS2304: Cannot find name '_getSlottedElements'.

26     private [_getSlottedElements];

但是消费者到底为什么会抱怨私有变量,而消费者根本不应该对此一无所知呢?

奇怪的是,quizzly 项目本身在 typescript 编译期间没有报告错误,这只影响使用.d.ts文件的消费者

今天打字稿中有哪些策略可以实现一些隐私?

标签: typescriptsymbolsprivacy

解决方案


既不通过添加下划线前缀也不通过使用符号(甚至不作为选项)

我不同意。_foovs.foo对我来说很私密。长期以来(2007 年),它一直是 JavaScript 中的一种模式。

打字稿“私人”关键字没有做任何事情来表明隐私意图,

它适用于 TypeScript 消费者。JavaScript 消费者知道_,至少如果他们使用任何其他编译为 es5 的纯 JS 项目(绝大多数)

我的建议

private _something


推荐阅读