typescript-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TypeScript best practices

TypeScript最佳实践

Apply the type-system-discipline principle skill first; this skill grounds it in TypeScript syntax.
RuleSummary
Discriminated unionsModel variants with a
kind
literal discriminant so impossible states can't be represented. No optional-field bags.
Branded typesBrand primitives with
& { readonly __brand: "X" }
so they can't be mixed up. Validate once at creation.
unknown
over
any
External data is
unknown
.
any
disables type checking everywhere it touches.
No
as
casts
Every
as
is a runtime crash waiting. Cast only after validation.
Narrowing hierarchyDiscriminant switch >
in
operator >
typeof
/
instanceof
> user-defined type guard >
as
.
Type guardsMust verify the claim. A lying guard is worse than
as
because the bug hides behind a name that says it's safe. Name them
isX
or
hasX
.
ExhaustivenessInline
const _exhaustive: never = x;
in default arms so the compiler errors when a new variant is added.
satisfies
over
as
Validates the value without widening literal types.
Boundary validationValidate where data crosses in; trust types inside. See the boundary-discipline principle skill.
Schema-derived typesReach for
Pick
/
Omit
/
Parameters
/
ReturnType
/
Awaited
/
typeof
before declaring a new interface.
Object argsPass objects, not positional, so argument order is self-documenting. Skip on hot paths (per-frame render, tokenizers, parsers).
Examples:
references/patterns.md
.
首先应用类型系统规范原则技能;该技能基于TypeScript语法。
规则总结
可区分联合使用
kind
字面量判别式建模变体,这样就无法表示不可能的状态。不要使用可选字段集合。
品牌类型
& { readonly __brand: "X" }
标记原始类型,防止它们被混淆。仅在创建时验证一次。
优先使用
unknown
而非
any
外部数据类型为
unknown
any
会禁用它所涉及的所有类型检查。
禁止使用
as
类型断言
每个
as
都可能导致运行时崩溃。仅在验证后进行断言。
类型收窄优先级判别式switch >
in
运算符 >
typeof
/
instanceof
> 用户定义类型守卫 >
as
类型守卫必须验证断言内容。一个错误的守卫比
as
更糟糕,因为bug会隐藏在看似安全的名称背后。命名为
isX
hasX
穷尽性检查在默认分支中添加内联
const _exhaustive: never = x;
,这样当添加新变体时编译器会报错。
优先使用
satisfies
而非
as
在不拓宽字面量类型的情况下验证值。
边界验证在数据进入的地方进行验证;内部信任类型。请参阅边界规范原则技能。
模式派生类型在声明新接口之前,优先使用
Pick
/
Omit
/
Parameters
/
ReturnType
/
Awaited
/
typeof
对象参数传递对象而非位置参数,这样参数顺序是自文档化的。在热路径(每帧渲染、分词器、解析器)上可跳过此规则。
示例:
references/patterns.md
.