前端TypeScript高级技巧让你的代码更安全毒舌时刻前端TypeScript这不是增加工作量吗JavaScript就够了为什么要用TypeScript——结果类型错误频发调试困难TypeScript太严格了我写起来很麻烦——结果代码质量差维护困难我只在关键地方用TypeScript其他地方用any——结果失去了TypeScript的意义。醒醒吧TypeScript不是负担而是提高代码质量的利器为什么你需要这个类型安全在编译时发现类型错误代码提示提供更好的IDE智能提示重构安全重构代码时更加安全可读性代码更加清晰易懂可维护性减少运行时错误提高代码可维护性反面教材// 反面教材过度使用any function processData(data: any) { // 没有类型检查容易出错 return data.name.toUpperCase(); } // 反面教材类型定义不完整 interface User { id: number; name: string; // 缺少email等其他属性 } // 反面教材类型断言滥用 function getUser(id: number): User { // 不安全的类型断言 return fetch(/api/users/${id}).then(res res.json()) as unknown as User; }正确的做法// 正确的做法使用泛型 function identityT(arg: T): T { return arg; } // 使用泛型约束 interface Lengthwise { length: number; } function loggingIdentityT extends Lengthwise(arg: T): T { console.log(arg.length); return arg; } // 正确的做法使用联合类型和类型守卫 type Shape Circle | Square; interface Circle { kind: circle; radius: number; } interface Square { kind: square; sideLength: number; } function getArea(shape: Shape): number { // 类型守卫 if (shape.kind circle) { return Math.PI * shape.radius ** 2; } else { return shape.sideLength ** 2; } } // 正确的做法使用类型推断 const user { id: 1, name: 张三, email: zhangsanexample.com }; // TypeScript会自动推断user的类型 // 正确的做法使用映射类型 interface Person { name: string; age: number; } // 生成只读类型 type ReadonlyPerson ReadonlyPerson; // 生成可选类型 type PartialPerson PartialPerson; // 生成必填类型 type RequiredPerson RequiredPartialPerson; // 正确的做法使用条件类型 // 提取Promise的返回类型 type UnwrapPromiseT T extends Promiseinfer U ? U : T; // 测试 async function fetchData(): Promisestring { return data; } // 类型会被推断为string let data: UnwrapPromiseReturnTypetypeof fetchData; // 正确的做法使用模板字面量类型 type EventNameT extends string ${T}Changed; type MouseEventName EventNameclick | mouseover | mouseout; // 类型为 clickChanged | mouseoverChanged | mouseoutChanged // 正确的做法使用类型别名和接口 // 类型别名 type UserID number; type UserName string; type Email string; // 接口 interface User { id: UserID; name: UserName; email: Email; createdAt: Date; updatedAt: Date; } // 正确的做法使用枚举 enum Role { Admin admin, User user, Guest guest } function checkPermission(role: Role): boolean { return role Role.Admin; } // 正确的做法使用命名空间 namespace Validation { export interface StringValidator { isAcceptable(s: string): boolean; } const lettersRegexp /^[A-Za-z]$/; const numberRegexp /^[0-9]$/; export class LettersOnlyValidator implements StringValidator { isAcceptable(s: