TypeScript 最佳实践指南
原创2024/1/5大约 2 分钟
TypeScript 最佳实践指南
TypeScript 为 JavaScript 添加了静态类型系统,帮助我们写出更健壮、可维护的代码。
为什么使用 TypeScript
- ✅ 类型安全,减少运行时错误
- ✅ 更好的 IDE 支持和代码提示
- ✅ 更容易重构代码
- ✅ 自文档化的代码
基础类型
// 基本类型
let isDone: boolean = false
let age: number = 25
let name: string = "ClownF"
let list: number[] = [1, 2, 3]
let tuple: [string, number] = ["hello", 10]
// 枚举
enum Color {
Red,
Green,
Blue
}
let c: Color = Color.Green
// Any 和 Unknown
let notSure: any = 4
let value: unknown = "hello"
// Void、Null 和 Undefined
function warnUser(): void {
console.log("Warning!")
}接口和类型别名
// 接口
interface User {
id: number
name: string
email?: string // 可选属性
readonly createdAt: Date // 只读属性
}
// 类型别名
type ID = string | number
type Point = {
x: number
y: number
}
// 联合类型
type Status = 'pending' | 'success' | 'error'
// 交叉类型
type Admin = User & {
role: 'admin'
permissions: string[]
}泛型
// 泛型函数
function identity<T>(arg: T): T {
return arg
}
// 泛型接口
interface GenericIdentityFn<T> {
(arg: T): T
}
// 泛型类
class GenericNumber<T> {
zeroValue: T
add: (x: T, y: T) => T
}
// 泛型约束
interface Lengthwise {
length: number
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length)
return arg
}高级类型
// 映射类型
type Readonly<T> = {
readonly [P in keyof T]: T[P]
}
type Partial<T> = {
[P in keyof T]?: T[P]
}
// 条件类型
type TypeName<T> =
T extends string ? "string" :
T extends number ? "number" :
T extends boolean ? "boolean" :
"object"
// 工具类型
interface Todo {
title: string
description: string
completed: boolean
}
type TodoPreview = Pick<Todo, "title" | "completed">
type TodoInfo = Omit<Todo, "completed">
type TodoReadonly = Readonly<Todo>
type TodoPartial = Partial<Todo>装饰器
// 类装饰器
function sealed(constructor: Function) {
Object.seal(constructor)
Object.seal(constructor.prototype)
}
@sealed
class Greeter {
greeting: string
constructor(message: string) {
this.greeting = message
}
}
// 方法装饰器
function log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value
descriptor.value = function(...args: any[]) {
console.log(`Calling ${propertyKey} with`, args)
return originalMethod.apply(this, args)
}
return descriptor
}
class Calculator {
@log
add(a: number, b: number) {
return a + b
}
}实用技巧
1. 类型守卫
function isString(value: unknown): value is string {
return typeof value === 'string'
}
if (isString(value)) {
console.log(value.toUpperCase())
}2. 断言函数
function assertIsNumber(value: unknown): asserts value is number {
if (typeof value !== 'number') {
throw new Error('Not a number')
}
}3. 索引签名
interface StringMap {
[key: string]: string
}
const config: StringMap = {
apiUrl: 'https://api.example.com',
timeout: '5000'
}配置建议
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"esModuleInterop": true,
"skipLibCheck": true
}
}最佳实践
- 启用严格模式:
"strict": true - 避免使用 any: 尽可能使用具体类型
- 善用类型推断: 让 TS 自动推断类型
- 使用只读属性: 防止意外修改
- 编写类型安全的代码: 利用类型系统捕获错误
总结
TypeScript 是现代前端开发的标配,掌握它能显著提升代码质量和开发效率。