[ PROMPT_NODE_25584 ]
typescript-cheatsheet
[ SKILL_DOCUMENTATION ]
# TypeScript 速查表
## 类型基础
typescript
// 原始类型
const name: string = 'John'
const age: number = 30
const isActive: boolean = true
const nothing: null = null
const notDefined: undefined = undefined
// 数组
const numbers: number[] = [1, 2, 3]
const strings: Array = ['a', 'b', 'c']
// 元组
const tuple: [string, number] = ['hello', 42]
// 对象
const user: { name: string; age: number } = { name: 'John', age: 30 }
// 联合类型
const value: string | number = 'hello'
// 字面量类型
const direction: 'up' | 'down' | 'left' | 'right' = 'up'
// Any 与 Unknown
const anyValue: any = 'anything' // ❌ 避免使用
const unknownValue: unknown = 'safe' // ✅ 推荐使用,需要类型收窄
## 类型别名与接口
typescript
// 类型别名
type Point = {
x: number
y: number
}
// 接口(对象首选)
interface User {
id: string
name: string
email?: string // 可选
readonly createdAt: Date // 只读
}
// 继承
interface Admin extends User {
permissions: string[]
}
// 交叉类型
type AdminUser = User & { permissions: string[] }
## 泛型
typescript
// 泛型函数
function identity(value: T): T {
return value
}
// 带约束的泛型
function getLength(item: T): number {
return item.length
}
// 泛型接口
interface ApiResponse {
data: T
status: number
message: string
}
// 带默认值的泛型
type Container = {
value: T
}
// 多泛型
function merge(obj1: T, obj2: U): T & U {
return { ...obj1, ...obj2 }
}
## 工具类型
typescript
interface User {
id: string
name: string
email: string
age: number
}
// Partial - 全部可选
type PartialUser = Partial
// Required - 全部必选
type RequiredUser = Required
// Readonly - 全部只读
type ReadonlyUser = Readonly
// Pick - 选择属性
type UserName = Pick
// Omit - 排除属性
type UserWithoutEmail = Omit
// Record - 键值映射
type UserMap = Record
// Extract - 从联合类型中提取
type StringOrNumber = string | number | boolean
type OnlyStrings = Extract
// Exclude - 从联合类型中排除
type NotString = Exclude
// NonNullable - 移除 null/undefined
type MaybeString = string | null | undefined
type DefinitelyString = NonNullable
// ReturnType - 获取函数返回值类型
function ge