TypeScript 是 JavaScript 的超集,它通过静态类型检查在编译阶段发现潜在错误。对于中大型前端项目,TypeScript 已经是事实标准。本文从基础类型出发,介绍一些工程中常用的实践技巧。

1. 为什么选择 TypeScript

  • 提前发现错误:在编码和编译阶段就能捕获类型不匹配、属性缺失等问题。
  • 提升可维护性:类型即文档,清晰的接口定义让代码更易读懂。
  • 增强 IDE 体验:自动补全、跳转定义、重构支持都依赖类型信息。

2. 基础类型速览

1
2
3
4
5
let name: string = 'Galaxy'
let age: number = 25
let isActive: boolean = true
let hobbies: string[] = ['coding', 'music']
let user: { name: string; age: number } = { name: 'Galaxy', age: 25 }

接口与类型别名

1
2
3
4
5
6
7
interface User {
name: string
age: number
email?: string // 可选属性
}

type ID = string | number

interfacetype 大部分场景可以互换,但 interface 支持声明合并,type 更灵活(支持联合类型、交叉类型)。

3. 泛型:让类型也具备复用能力

泛型(Generics)是 TypeScript 最强大的特性之一,它允许你在定义时不指定具体类型,使用时再传入:

1
2
3
4
5
6
function identity<T>(arg: T): T {
return arg
}

identity<string>('hello')
identity<number>(42)

在 React 中,泛型同样无处不在:

1
2
3
4
5
6
7
8
interface Props<T> {
items: T[]
renderItem: (item: T) => React.ReactNode
}

function List<T>({ items, renderItem }: Props<T>) {
return <ul>{items.map(renderItem)}</ul>
}

4. 常用内置工具类型

TypeScript 提供了大量工具类型,帮助我们从已有类型派生新类型:

工具类型 作用
Partial<T> 将 T 的所有属性变为可选
Required<T> 将 T 的所有属性变为必填
Pick<T, K> 从 T 中挑选出 K 属性
Omit<T, K> 从 T 中排除 K 属性
Record<K, T> 构造一个键为 K、值为 T 的对象类型

示例:

1
2
type UserPreview = Pick<User, 'name' | 'age'>
type UserForm = Partial<User>

5. 类型断言与类型守卫

类型断言

当你比编译器更了解某个值的类型时,可以使用类型断言:

1
const canvas = document.getElementById('canvas') as HTMLCanvasElement

类型守卫

在运行时缩窄类型范围:

1
2
3
4
5
6
7
function printLength(value: string | number) {
if (typeof value === 'string') {
console.log(value.length) // 此处 value 被缩窄为 string
} else {
console.log(value.toFixed(2)) // 此处 value 被缩窄为 number
}
}

6. 配置 tsconfig.json

一个合理的前端 tsconfig.json 通常包含:

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"jsx": "react-jsx"
},
"include": ["src/**/*"]
}

开启 strict: true 能最大程度发挥 TypeScript 的类型安全优势。

总结

TypeScript 的学习曲线并不陡峭,但收益非常明显。从给变量加上类型开始,逐步掌握接口、泛型和工具类型,你的代码质量和开发效率都会有质的提升。