点赞收藏关注不迷路!
你是不是经常在用 TypeScript,却总感觉“还差点火候”?
其实,TS 的威力并不只在于类型检查,更在于那些你可能漏掉的小技巧:它们不复杂,却能显著提升代码的安全性、可读性、工程效率!
本文为你整理了 10 个容易被忽略、但非常实用的 TypeScript 技巧,看完一定会让你的项目更“Type Safety”。
type ButtonType = 'primary' | 'danger' | 'success'
function createButton(type: ButtonType) {}
好处:比字符串常量更安全、更智能补全,避免拼写错误。
as const
固定值为字面量类型const status = ['success', 'error', 'loading'] as const
type Status = typeof status[number] // 'success' | 'error' | 'loading'
常用于:将数组/对象转换成精确的联合类型。
keyof typeof
构造安全键名类型const COLORS = {
success: '#0f0',
danger: '#f00',
info: '#00f'
}
type ColorKey = keyof typeof COLORS // 'success' | 'danger' | 'info'
适用场景:配置映射、主题变量、权限字段校验。
function fetchData(url = '/api/user') {
// url 自动推断为 string
}
很多人忘了:有默认值就会自动变成非必选参数,无需额外写 url?: string
。
infer
提取复杂类型中的子类型type GetPromiseType<T> = T extends Promise<infer R> ? R : never
type Result = GetPromiseType<Promise<string>> // string
高阶用法,但非常实用,常见于库源码(如 Vue、React)。
ReturnType
自动推导类型function useUser() {
return { name: 'Jin', age: 28 }
}
type User = ReturnType<typeof useUser>
不需要手写 { name: string; age: number }
,更安全且 DRY。
Record
构建对象映射类型type Role = 'admin' | 'user' | 'guest'
type RoleMap = Record<Role, string>
// => { admin: string; user: string; guest: string }
常用于权限、国际化词典、配置表。
unknown
更安全function isString(val: unknown): val is string {
return typeof val === 'string'
}
function print(value: unknown) {
if (isString(value)) {
console.log(value.toUpperCase()) // ✅ 安全使用 string 方法
}
}
防止滥用类型断言,提升运行时安全。
satisfies
强约束对象结构不丢失字面量信息(TS 4.9+)const theme = {
dark: '#000',
light: '#fff'
} satisfies Record<'dark' | 'light', string>
比 as
更智能:确保结构完整,同时保留精确值类型。
readonly
限制传入对象修改(函数签名更安全)function printUser(user: Readonly<{ name: string }>) {
// user.name = 'xx' ❌ 报错,防止误修改
}
常用于工具库、暴露给外部的函数接口参数,增强不可变性。
ts-toolbelt
可以引入 ts-toolbelt:
import { Merge, Optional, Omit } from 'ts-toolbelt'
它提供了比原生更强大的类型组合能力,非常适合中大型项目!
技巧 | 关键词 | 适用场景 |
---|---|---|
联合类型 + as const |
精准值约束 | 状态机、按钮类型 |
ReturnType / keyof |
类型复用 | 函数输出、对象字段 |
Record |
映射类型 | 权限配置、字典表 |
infer |
类型提取 | 工具泛型、接口抽象 |
satisfies |
双保险校验 | 避免误写常量对象 |
掌握这些小技巧,让你的项目类型系统更严谨,同时不啰嗦!
如果这篇文章帮你发现了一两个从没用过的 TypeScript 小技巧,别忘了点个 点赞 + 收藏 + 关注,让我继续有动力写更多实用 TS 篇!
下一篇我可以写:
《你可能忽略的 TypeScript 类型兼容性与类型推导原理》