示例工程 07-classes-interfaces

07-classes-interfaces/04-private-fields/README.md

markdown · 1.0 KB

运行:07 · private-fields

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

# 04 · private-fields
 
**演示**:`private` 是编译期检查,实例上仍是普通属性;`#value` 是真正的运行时私有字段。
**运行**:在 `tutorials/typescript` 下执行 `npm run build`,再执行 `npm run serve`,打开
`http://localhost:8080/examples/07-classes-interfaces/04-private-fields/`;开 Console。
**预期控制台输出**:
```text
legacy
hash
value
(no own keys)
```
**类型检查**:`node node_modules/typescript/bin/tsc -p examples/07-classes-interfaces/04-private-fields/tsconfig.types.json`
**预期类型错误**(`demo/access.ts`,由 `tsconfig.fail.json` 触发):
```text
demo/access.ts(21,18): error TS2341: Property 'value' is private and only accessible within class 'LegacySecret'.
demo/access.ts(22,16): error TS18013: Property '#value' is not accessible outside class 'HashSecret' because it has a private identifier.
```
**注意**:`#private` 不能被 `Object.keys` 枚举,也不能被 `JSON.stringify` 序列化。