TypeScript 核心知识
2026/11/25大约 3 分钟
TypeScript 核心知识
一、类型注解与推断
TypeScript 会优先根据赋值推断类型,能推断出来时不必重复标注。
let count = 0 // number
const name = 'vue' // 'vue'(字面量类型)
function add(a: number, b: number): number {
return a + b
}三个特殊类型:
any:关闭类型检查,尽量少用。unknown:未知类型,使用前必须先收窄。never:不会正常返回的类型,如抛错函数、穷尽检查。
二、interface 与 type
interface User {
id: number
name: string
}
type Point = { x: number; y: number }
type ID = string | number选择建议:
- 对象结构、需要声明合并或
extends时用interface。 - 联合类型、交叉类型、映射类型、条件类型用
type。 - 同一项目内保持一致,不要为了“哪个更强”反复摇摆。
三、泛型
泛型让类型与值一起复用。
function first<T>(list: T[]): T | undefined {
return list[0]
}
function pick<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key]
}extends用于约束类型参数。- 泛型默认值:
type Box<T = string> = { value: T }。 - 不要为了“高级”而滥用泛型;能从参数推断时让 TS 自己推断。
四、联合、交叉与字面量
type Status = 'idle' | 'loading' | 'success' | 'error'
type Result =
| { status: 'success'; data: string }
| { status: 'error'; message: string }可辨识联合(discriminated union)配合 switch 可以做穷尽检查,是业务状态建模的常用方式。
as const 可以把对象和数组收窄为只读字面量:
const routes = ['home', 'about'] as const
type Route = (typeof routes)[number] // 'home' | 'about'五、类型收窄
function format(value: string | number) {
if (typeof value === 'string') {
return value.trim()
}
return value.toFixed(2)
}常用手段:
typeof、instanceof、in- 真值判断、相等判断
- 自定义类型守卫:
function isUser(v: unknown): v is User - 断言函数:
asserts value is User
优先用收窄,少用 as。as 只是告诉编译器“相信我”,不会做运行时检查。
六、常用工具类型
interface User {
id: number
name: string
email?: string
}
type PartialUser = Partial<User> // 全部可选
type RequiredUser = Required<User> // 全部必填
type UserName = Pick<User, 'name'> // 挑选字段
type UserWithoutEmail = Omit<User, 'email'> // 排除字段
type UserMap = Record<string, User> // 键值映射
type FnReturn = ReturnType<() => void> // 函数返回值其他常用:Parameters、NonNullable、Awaited、Exclude、Extract。
七、tsconfig 关键项
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"jsx": "preserve",
"noUncheckedIndexedAccess": true,
"skipLibCheck": true,
"paths": {
"@/*": ["./src/*"]
}
}
}strict: true是底线,新项目不要关闭。moduleResolution与构建工具保持一致;Vite 项目常用Bundler。paths只影响类型解析,运行时别名还需要构建工具同步配置。skipLibCheck可以跳过第三方声明文件检查,但不能替代修复自己的类型错误。
八、与 Vue / React 集成
Vue 3:
const props = defineProps<{ title: string; count?: number }>()
const emit = defineEmits<{ (e: 'change', value: number): void }>()React:
type ButtonProps = {
children: React.ReactNode
onClick?: () => void
}
function Button({ children, onClick }: ButtonProps) {
return <button onClick={onClick}>{children}</button>
}九、常见易错点
- 用
any绕过报错,最后类型系统形同虚设。 - 用
as强行断言,掩盖真实的运行时错误。 - 对象字面量直接赋给接口时触发“多余属性检查”,先赋值给变量或调整类型。
- 泛型推断失败时先检查参数是否给了足够信息,而不是直接手写全部类型参数。
- 只写类型不写运行时校验;来自接口、表单、
localStorage的数据仍需运行时验证。
