typescript-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypeScript best practices
TypeScript 最佳实践
Apply the type-system-discipline principle skill first.
| Rule | Summary |
|---|---|
| Discriminated unions | Model variants with a |
| Branded types | Brand primitives with |
| Constructive modeling | Build the shape so the illegal value can't be constructed. |
| Simplest total type | Keep |
| External data is |
| Schemas before guards | Before hand-writing a property-by-property type guard, use the repository's runtime schema library and infer the type from the schema, such as |
No | Every |
| Narrowing hierarchy | Discriminant switch > |
| Type guards | Must verify the claim. A lying guard is worse than |
| Exhaustiveness | Inline |
| Validates the value without widening literal types. |
| Boundary validation | Parse where data crosses in, into a named domain type. |
| Schema-derived types | Reach for |
| Object args | Pass objects, not positional, so argument order is self-documenting. Skip on hot paths (per-frame render, tokenizers, parsers). |
| Real tests | Don't mock what you can run. Prefer the framework's real test primitives with leak/disposable checks, and verify UI in a running build. Mock only what you can't run locally. |
| Structured telemetry | Prefer structured logger diagnostics with enough context to debug from an id. No |
Examples: .
references/patterns.md首先应用 type-system-discipline 原则 skill。
| 规则 | 摘要 |
|---|---|
| 判别联合(Discriminated unions) | 使用 |
| 品牌类型(Branded types) | 使用 |
| 构造式建模(Constructive modeling) | 通过类型结构让非法值无法被构造。非空使用 |
| 最简单的全函数类型(Simplest total type) | 只要其上的每个操作都是 total,就保留 |
| 外部数据应视为 |
| Schema 优先于类型守卫 | 在手写逐属性类型守卫之前,使用仓库的运行时 schema 库,并从 schema 推断类型,例如 |
禁止 | 每个 |
| 收窄层级(Narrowing hierarchy) | 判别符 switch > |
| 类型守卫(Type guards) | 必须验证所作的断言。会说谎的类型守卫比 |
| 穷尽性(Exhaustiveness) | 在 default 分支中内联 |
| 在不拓宽字面量类型的情况下验证值。 |
| 边界验证(Boundary validation) | 在数据进入系统时进行解析,并转换为命名的领域类型。 |
| Schema 派生类型(Schema-derived types) | 声明新的 interface 之前,先考虑 |
| 对象参数(Object args) | 传递对象而不是位置参数,使参数顺序一目了然。在 hot path 中不要这样做(逐帧渲染、tokenizer、parser)。 |
| 真实测试(Real tests) | 凡是能够实际运行的部分都不要 mock。优先使用框架真实的测试原语,并进行 leak/disposable 检查;在运行中的构建中验证 UI。只 mock 无法在本地运行的部分。 |
| 结构化遥测(Structured telemetry) | 优先使用包含足够上下文的结构化 logger 诊断信息,以便仅凭 id 就能进行调试。正式发布的代码中不要使用 |
示例:。
references/patterns.md