示例工程 03-literal-types-narrowing

03-literal-types-narrowing/02-typeof-narrowing/README.md

markdown · 0.8 KB

运行:03 · typeof-narrowing

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

# 02 · typeof-narrowing
 
**演示**:`typeof` 与 `=== null` 把 `string | string[] | null` 逐步收窄到可以安全使用的分支。
**运行**:在 `tutorials/typescript` 下执行 `npm run build`,再执行 `npm run serve`,打开
`http://localhost:8080/examples/03-literal-types-narrowing/02-typeof-narrowing/`;开 Console。
**预期控制台输出**:
```text
ts
a
(empty)
(null)
```
**类型检查**:`node node_modules/typescript/bin/tsc -p examples/03-literal-types-narrowing/02-typeof-narrowing/tsconfig.types.json`
**预期类型错误**(`demo/closure.ts`,由 `tsconfig.fail.json` 触发):
```text
demo/closure.ts(6,24): error TS18048: 'value' is possibly 'undefined'.
```
**注意**:闭包里的收窄只在「之后没有再赋值」时保留;`value = undefined` 之后回到 `string | undefined`。