typescript - 在 TypeScript 中,为什么 Symbols for Privacy 会向消费者抛出错误?
问题描述
我希望我的一些类字段和方法有一些隐私
- 我知道符号并不是真正私人的,但我只是不希望“私人”成员只是四处飘荡以供人们轻松使用,这是关于信号意图
- 打字稿“私人”关键字没有做任何事情来表明隐私意图,既不是通过添加下划线前缀也不是通过使用符号(甚至不是作为选项)
- 我不想等待打字稿来实现私有字段
#
提案,也不想现在切换到 babel
在我的项目中,我创建了一些使用符号来访问私有成员的类
模式基本上是:
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
文件的消费者
今天打字稿中有哪些策略可以实现一些隐私?
解决方案
既不通过添加下划线前缀也不通过使用符号(甚至不作为选项)
我不同意。_foo
vs.foo
对我来说很私密。长期以来(2007 年),它一直是 JavaScript 中的一种模式。
打字稿“私人”关键字没有做任何事情来表明隐私意图,
它适用于 TypeScript 消费者。JavaScript 消费者知道_
,至少如果他们使用任何其他编译为 es5 的纯 JS 项目(绝大多数)
我的建议
private _something
推荐阅读
- azure-logic-apps - 如何在逻辑应用中将 csv 转换为 xml
- docker - COS:如何重启有新镜像的容器?
- python - 如何修复我的碰撞,这样我就可以站在盒子上而不会从盒子上掉下来
- python - 从 txt 文件下载链接
- c++ - GCC 的尖括号实现包括。为什么它必须如下所述?
- python - 如何在循环中获取 Python TkInter 多个组合框中的选定项目?
- php - 为什么我的组件(位于 foreach 循环之外)被循环通过?
- r - 我可以让这个 R foreach 循环更快吗?
- window - 雪花窗函数
- c# - 如何通过 ObjectId 获取数组/元素中的元素