/pstack:typescript-best-practices
按需点名一句话把类型原则变成 TypeScript 的写法,比如每种情况都处理到。
- 什么时候用
- 改的是 .ts / .tsx 文件。它不会自己加载,要你点名。
/pstack:typescript-best-practices用它和不用它
同一件事,直接跟 AI 说,和点名用 /pstack:typescript-best-practices,AI 的做法不一样:
用 /pstack:typescript-best-practicesas 把类型硬转过去,先让编译通过在数据进来的地方先校验,校验过了才转类型kind 标记,不可能的组合写不出来any外部数据标成 unknown,用项目的 schema 库解析文档写了什么
约 350 个英文单词,中文译文约 650 字,读完约 2 分钟。
开头先套用 type-system-discipline 原则,再给一张 16 条规则的表,从用 kind 区分情况、外部数据用 unknown,到测试少 mock、发布的代码不留 console.log。例子放在 references/patterns.md。
写法亮点
挑了几句原文:每句让 AI 做什么、为什么这样写管用、你写提示词时怎么借来用。
先指向总原则再给细则
Apply the type-system-discipline principle skill first.
先套用 type-system-discipline 这个原则技能。
- 让 AI
- 它先按通用的类型原则想清楚,再用下面的 TypeScript 写法落到代码里,表里没写到的情况也有章可循。
- 为什么管用
- 细则总有列不全的时候;开头一句指向背后的总原则,AI 遇到表外的情况就知道该往哪个方向判断。
- 借来用
- 给一串具体要求前先说总目标:「总原则是让老人一眼看懂;下面几条只是例子:字大、少按钮、不用英文。」
用一行排好先后
Discriminant switch >
inoperator >typeof/instanceof> user-defined type guard >as.按标记 switch >
in运算符 >typeof/instanceof> 自定义类型守卫 >as。- 让 AI
- 要判断数据是哪种类型时,它从最可靠的写法开始用,
as只当最后一招。 - 为什么管用
- 一串「>」把好几种做法排成一条队,AI 一眼就知道先试哪个、哪个是下策,不用逐个解释。
- 借来用
- 有几种做法时直接排个序:「先查官方文档 > 再看 GitHub issue > 最后才看博客。」
点破看似更好的做法
A lying guard is worse than
asbecause the bug hides behind a name that says it's safe.一个撒谎的守卫比
as更糟,因为 bug 藏在一个说它很安全的名字后面。- 让 AI
- 它写的
isX函数会真的检查每个字段,不会写一个名字好听、其实什么都不查的空壳。 - 为什么管用
- AI 以为「换个正式的写法」就算改进;直接说明这种写法为什么更危险,就挡住了表面合规。
- 借来用
- 遇到容易走形式的地方先点破:「加了 try/catch 却什么都不处理,比不加更糟,因为错误被藏起来了。」
规则后面紧跟例外
Skip on hot paths (per-frame render, tokenizers, parsers).
热点路径上不用(每帧渲染、分词器、解析器)。
- 让 AI
- 它平时用对象传参,但在每帧都要跑的代码里不会为了守规矩把性能拖慢。
- 为什么管用
- 例外和规则写在同一格,还给了具体场景,AI 就不会死守规则,也不会把例外扩大到别处。
- 借来用
- 立规矩时顺手写上例外:「回复都用中文;但报错信息和命令原样保留英文。」
全文
AI 读到的就是这份 SKILL.md。可以看中文、看原文,或者一段一段对照着看。
descriptionTypeScript best practices. Use when reading or editing any .ts or .tsx file.
descriptionTypeScript 的最佳写法。读或改任何 .ts 或 .tsx 文件时使用。
TypeScript best practices
TypeScript best practices(TypeScript 最佳写法)
Apply the type-system-discipline principle skill first.
先套用 type-system-discipline 这个原则技能。
| Rule | Summary |
|---|---|
| Discriminated unions | Model variants with a kind literal discriminant so impossible states can't be represented. No optional-field bags. |
| Branded types | Brand primitives with & { readonly __brand: "X" } so they can't be mixed up. Validate once at the boundary. A brand comes from a verifying type guard (input is AgentId), never from as. |
| Constructive modeling | Build the shape so the illegal value can't be constructed. [T, ...T[]] for non-empty, [T, T][] for even length, start plus duration for a range. Not a runtime guard, not a wish for refinement types. |
| Simplest total type | Keep T[] while every operation on it stays total. Strengthen to NonEmpty<T> only where the loose type forces !, a cast, or a "should never happen" throw. |
unknown over any |
External data is unknown. |
| 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 z.infer. |
No as casts |
Every as is a runtime crash waiting. Cast only after validation. |
| Narrowing hierarchy | Discriminant switch > in operator > typeof/instanceof > user-defined type guard > as. |
| Type guards | Must 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. |
| Exhaustiveness | Inline 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 validation | Parse where data crosses in, into a named domain type. Record<string, unknown> (however spelled) stops at that parse. Trust types inside. See the boundary-discipline principle skill. |
| Schema-derived types | Reach for Pick/Omit/Parameters/ReturnType/Awaited/typeof before declaring a new interface. |
| 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 console.log in shipped code. |
| 规则 | 要点 |
|---|---|
| 可辨识联合 | 用一个 kind 字面量做标记来表示几种变体,让不可能的状态根本写不出来。不要用一袋可选字段。 |
| 品牌类型 | 用 & { readonly __brand: "X" } 给基本类型打上品牌,让它们没法被混用。在边界上校验一次。品牌只能来自一个真正做了校验的类型守卫(input is AgentId),绝不能来自 as。 |
| 用结构来建模 | 把类型的形状搭成非法的值根本造不出来。非空用 [T, ...T[]],偶数长度用 [T, T][],范围用 start 加 duration。不是靠运行时检查,也不是指望精化类型。 |
| 最简单的完备类型 | 只要对它的每个操作都能处理所有情况,就保持 T[]。只有在宽松的类型逼你用 !、类型断言,或者抛一个「不应该发生」的错误时,才收紧成 NonEmpty<T>。 |
用 unknown 不用 any |
外来数据一律是 unknown。 |
| 先用 schema 再写守卫 | 手写逐个属性检查的类型守卫之前,先用仓库里的运行时 schema 库,从 schema 推出类型,比如 z.infer。 |
不用 as 断言 |
每个 as 都是一个等着发生的运行时崩溃。只在校验之后才断言。 |
| 收窄类型的优先顺序 | 按标记 switch > in 运算符 > typeof/instanceof > 自定义类型守卫 > as。 |
| 类型守卫 | 必须真的校验它声称的事。一个撒谎的守卫比 as 更糟,因为 bug 藏在一个说它很安全的名字后面。命名为 isX 或 hasX。 |
| 穷尽检查 | 在 default 分支里直接写 const _exhaustive: never = x;,这样新加一种变体时编译器会报错。 |
用 satisfies 不用 as |
校验值,同时不把字面量类型放宽。 |
| 在边界上校验 | 在数据进来的地方解析,转成一个有名字的领域类型。Record<string, unknown>(不管怎么写)到这次解析就为止。进来之后就信任类型。见 boundary-discipline 原则技能。 |
| 从已有定义推导类型 | 声明新 interface 之前,先用 Pick/Omit/Parameters/ReturnType/Awaited/typeof。 |
| 用对象传参 | 传一个对象,不按位置传参,这样参数顺序一看就懂。热点路径上不用(每帧渲染、分词器、解析器)。 |
| 真实的测试 | 能跑的就别模拟。优先用框架真实的测试基础设施,并带上泄漏 / 资源释放检查;界面要在跑起来的构建里验证。只模拟本地跑不起来的东西。 |
| 结构化的运行记录 | 优先用结构化日志记录诊断信息,上下文要足够,光凭一个 id 就能排查。上线的代码里不留 console.log。 |
Examples: references/patterns.md.
示例:references/patterns.md。
原文作者 Lauren Tan(poteto),MIT 许可。译文由本站翻译,核对到 pstack 镜像 97de40d。 在 GitHub 上看