typescript-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TypeScript Patterns

TypeScript 模式

Overview

概述

Advanced TypeScript patterns that use the type system to prevent runtime errors. Focuses on strict mode TypeScript with patterns for type inference, narrowing, and compile-time validation. Not a beginner tutorial.
When to use: Building type-safe APIs, complex data transformations, library authoring, preventing runtime errors through types, working with strict mode flags.
When NOT to use: Learning TypeScript basics (primitives, interfaces, classes), JavaScript-to-TypeScript migration guidance, tooling setup, or build configuration.
利用类型系统避免运行时错误的高级TypeScript模式。聚焦于严格模式下的TypeScript,涵盖类型推断、类型收窄与编译时验证的相关模式。这不是入门教程。
适用场景: 构建类型安全的API、复杂数据转换、库开发、通过类型避免运行时错误、使用严格模式配置项。
不适用场景: 学习TypeScript基础知识(原始类型、接口、类)、JavaScript转TypeScript迁移指导、工具搭建或构建配置。

Quick Reference

速查参考

PatternAPIKey Points
Utility types
Pick<T, K>
,
Omit<T, K>
Extract or exclude properties
Partial/Required
Partial<T>
,
Required<T>
Make properties optional or required
Record type
Record<K, V>
Object with known keys
Awaited type
Awaited<T>
Unwrap Promise return types
ReturnType/Parameters
ReturnType<F>
,
Parameters<F>
Extract function types
Generic constraints
<T extends Type>
Constrain generic parameters
Type inference
type Inferred = typeof value
Let TypeScript infer from values
Type guards
typeof
,
instanceof
,
in
Narrow types at runtime
Custom type guards
(x): x is Type
User-defined narrowing functions
Inferred predicates
(x) => x !== null
Auto-inferred type predicate filters
Discriminated unionsUnion with literal
type
property
Exhaustive pattern matching
Conditional types
T extends U ? X : Y
Type-level conditionals
Mapped types
{ [K in keyof T]: T[K] }
Transform all properties
Template literals
`${A}-${B}`
String literal type manipulation
Const assertions
as const
Narrowest possible literal types
Satisfies operator
value satisfies Type
Type check without widening
NoInfer utility
NoInfer<T>
Prevent inference from a position
Const type params
<const T extends Type>
Narrow inference without
as const
Inline type imports
import { type User }
Import types explicitly
Module augmentation
declare module 'lib' { ... }
Extend third-party types
Assertion functions
function assert(x): asserts x is T
Throw if type guard fails
模式API核心要点
工具类型
Pick<T, K>
,
Omit<T, K>
提取或排除属性
可选/必填转换
Partial<T>
,
Required<T>
将属性设为可选或必填
Record类型
Record<K, V>
拥有已知键的对象
Awaited类型
Awaited<T>
解开Promise返回类型
返回值/参数类型提取
ReturnType<F>
,
Parameters<F>
提取函数的类型信息
泛型约束
<T extends Type>
约束泛型参数
类型推断
type Inferred = typeof value
让TypeScript从值中自动推断类型
类型守卫
typeof
,
instanceof
,
in
在运行时收窄类型范围
自定义类型守卫
(x): x is Type
用户自定义的类型收窄函数
自动推断谓词
(x) => x !== null
自动推断的类型谓词过滤器
可辨识联合包含字面量
type
属性的联合类型
穷尽式模式匹配
条件类型
T extends U ? X : Y
类型层面的条件判断
映射类型
{ [K in keyof T]: T[K] }
转换对象的所有属性
模板字面量类型
`${A}-${B}`
字符串字面量类型的操作
Const断言
as const
获得最窄的字面量类型
Satisfies操作符
value satisfies Type
类型检查同时保留窄类型
NoInfer工具类型
NoInfer<T>
阻止从特定位置进行类型推断
Const泛型参数
<const T extends Type>
无需
as const
即可收窄推断结果
内联类型导入
import { type User }
显式导入类型
模块扩充
declare module 'lib' { ... }
扩展第三方库的类型定义
断言函数
function assert(x): asserts x is T
若类型守卫验证失败则抛出错误

Common Mistakes

常见错误

MistakeCorrect Pattern
Using
any
without justification
Use
unknown
and narrow with type guards
Manual type assertions everywhereLet inference work, type function returns
Destructuring before type narrowingKeep object intact for discriminated unions
Index access without undefined checkEnable
noUncheckedIndexedAccess
as Type
casting unsafe values
Use
satisfies Type
to preserve narrow types
Inline objects in genericsExtract to
const
or type alias
Omitting
extends
in constraints
Always constrain generics when possible
Using
Parameters<typeof fn>[0]
Type the parameter directly in function
Not handling union exhaustivenessUse
never
checks in switch/if-else
value as const satisfies Type
Use
satisfies Type
then
as const
if needed
错误做法正确模式
无正当理由使用
any
使用
unknown
并通过类型守卫收窄类型
到处手动添加类型断言让TypeScript自动推断,仅为函数返回值指定类型
在类型收窄前解构对象保持对象完整以适配可辨识联合
未检查undefined就进行索引访问启用
noUncheckedIndexedAccess
配置项
as Type
转换不安全的值
使用
satisfies Type
保留窄类型
在泛型中直接使用内联对象提取为
const
变量或类型别名
约束中省略
extends
关键字
尽可能为泛型添加约束
使用
Parameters<typeof fn>[0]
在函数中直接为参数指定类型
未处理联合类型的穷尽性在switch/if-else中使用
never
类型检查
value as const satisfies Type
若需要则先使用
satisfies Type
再添加
as const

Delegation

任务委派

  • Pattern discovery: Use
    Explore
    agent to find existing patterns in codebase
  • Type error debugging: Use
    Task
    agent for multi-step type resolution
  • Code review: Delegate to
    code-reviewer
    skill for type safety audit
  • 模式发现:使用
    Explore
    agent在代码库中查找现有模式
  • 类型错误调试:使用
    Task
    agent进行多步骤类型解析
  • 代码审查:委派给
    code-reviewer
    技能进行类型安全审计

References

参考资料

  • Type utilities (Pick, Omit, Partial, Required, Record, Extract, Exclude, ReturnType, Parameters, Awaited)
  • Generics (constraints, inference, default parameters, variance)
  • Type guards and narrowing (typeof, instanceof, in, custom guards, assertion functions)
  • Discriminated unions (exhaustive checking, never type, tagged unions)
  • Conditional types (distributive conditionals, infer keyword, type-level logic)
  • Mapped types (key remapping, template literals, modifiers)
  • Strict mode patterns (noUncheckedIndexedAccess, exactOptionalPropertyTypes, const assertions, satisfies)
  • Module patterns (inline type imports, declaration files, module augmentation, ambient types)
  • Modern idioms (eslint-plugin-unicorn patterns, modern array/string/DOM APIs, ES modules)
  • 类型工具(Pick、Omit、Partial、Required、Record、Extract、Exclude、ReturnType、Parameters、Awaited)
  • 泛型(约束、推断、默认参数、方差)
  • 类型守卫与类型收窄(typeof、instanceof、in、自定义守卫、断言函数)
  • 可辨识联合(穷尽检查、never类型、标签联合)
  • 条件类型(分布式条件、infer关键字、类型层面逻辑)
  • 映射类型(键重映射、模板字面量、修饰符)
  • 严格模式模式(noUncheckedIndexedAccess、exactOptionalPropertyTypes、const断言、satisfies)
  • 模块模式(内联类型导入、声明文件、模块扩充、环境类型)
  • 现代惯用写法(eslint-plugin-unicorn模式、现代数组/字符串/DOM API、ES模块)