TypeScript 参考
通过可运行的 TypeScript 示例,学习验证 JSON、处理可选值,以及用可辨识联合类型表达结果。
运行示例
安装 TypeScript 和 Node.js 后,将每个示例单独保存为 example.ts,依次运行 tsc --strict example.ts 和 node example.js。
在运行时验证解析出的 JSON
先将解析结果赋给 unknown。使用数据前检查结构和字段类型。运行时检查通过后,类型守卫会收窄 TypeScript 类型。
typescript
type Config = { port: number };
function isConfig(value: unknown): value is Config {
return typeof value === "object" && value !== null &&
"port" in value && typeof value.port === "number";
}
const input: unknown = JSON.parse('{"port":8080}');
if (isConfig(input)) console.log(input.port);预期输出
8080常见误区
as Config 这样的类型断言不会验证输入。JSON 语法错误和字段值无效需要分别处理。
设置默认值时保留 false 和 0
只有 null 和 undefined 才应触发默认值时,使用空值合并运算符 ??。
typescript
type Options = { retries?: number; enabled?: boolean };
const options: Options = { retries: 0, enabled: false };
console.log(options.retries ?? 3, options.enabled ?? true);预期输出
0 false常见误区
|| 遇到 0、false 和空字符串也会回退。先确认这些值是否是有效输入。
用结果类型区分成功与失败
给每种结果一个不同的字面量标记。检查标记后,TypeScript 会根据分支提供对应字段。
typescript
type Result =
| { kind: "ok"; value: number }
| { kind: "error"; message: string };
function readCount(text: string): Result {
return /^\d+$/.test(text)
? { kind: "ok", value: Number(text) }
: { kind: "error", message: "Expected digits" };
}
for (const input of ["12", "12px"]) {
const result = readCount(input);
console.log(result.kind === "ok" ? result.value : result.message);
}预期输出
12
Expected digits常见误区
如果 value 和 error 都是可选字段,类型会允许两者都不存在。拆成不同分支可以排除这种状态。