跳转到内容
关系图谱

typescript-best-practices(pstack)

350 字 1 分钟

属性 8
repo
pstack
skill
typescript-best-practices
source
pstack/skills/typescript-best-practices/SKILL.md
invoke
user
phase
build
cost
low
status
stable
local
missing
一句话

一张 16 条的 TypeScript 规则表,把 pstack-原则集 落成具体语法:判别联合、brand、unknown、schema 先行、不 as。

何时用 ​

  • 适合:读或写 .ts、.tsx 文件时显式加载;frontmatter 里有 paths 匹配但作者建议按名调用。
  • 不适合:非 TS 代码;想要的是原则本身而不是语法细则。

怎么用 ​

text
/typescript-best-practices 这次改动涉及 .ts 文件,按规则表把关
  1. 建模:判别联合加 kind 字面量、brand 语义化 primitive、构造性建模让非法值造不出来。
  2. 边界:外部数据是 unknown,在边界 parse 成命名 domain type;优先仓库的 schema 库加 z.infer。
  3. 收窄层级:判别 switch > in > typeof/instanceof > 用户 type guard > as;guard 必须真验证,命名 isX/hasX。
  4. 工具:satisfies 优于 as,exhaustiveness 用 const _exhaustive: never,派生类型优先 Pick/Omit/Parameters/ReturnType/Awaited。
  5. 风格:对象参数替代位置参数(热路径除外)、真实测试少 mock、结构化日志不用 console.log。

产出 ​

  • 符合规则表的 TS 代码;示例在 references/patterns.md。

要点与坑 ​

  • 最松可用类型原则:T[] 够用就别急着上 NonEmpty<T>,只在被迫 !、cast、throw 时收紧。
  • 撒谎的 type guard 比 as 更糟,bug 躲在一个写着「安全」的名字后面。
  • 纯规则表,不依赖宿主功能,可直接当 lint 心则使用。

关联 ​