10个 TypeScript 习惯 每个 JavaScript 开发者都应养成 🚀
Source: Dev.to
TypeScript 不仅仅是另一个工具——它是你的调试助手、文档系统和代码安全网的集合。这 10 条习惯将永远改变你的编码方式。
1. 启用严格模式
始终在 tsconfig.json 中开启 strict 模式,以获得最全面的类型检查。
{
"compilerOptions": {
"strict": true
// …other options
}
}
2. 定义接口,而不仅仅是类型别名
虽然 type 别名和 interface 声明都可以描述对象结构,但接口是可扩展的,且非常适合定义契约。
interface User {
id: number;
name: string;
email: string;
}
3. 绝不使用 any
使用 any 会破坏 TypeScript 的意义。请优先使用 unknown、never 或合适的联合类型。
function process(value: unknown) {
// 在使用之前先缩小类型
}
4. 利用工具类型(Pick、Omit、Partial)
TypeScript 内置的工具类型可以高效地转换已有类型。
type User = { id: number; name: string; email: string };
type PartialUser = Partial; // all fields optional
type UserName = Pick; // only the name field
type UserWithoutEmail = Omit; // all except email
5. 使用类型守卫
typeof、instanceof 以及自定义检查可以安全地缩小联合类型。
function isString(value: unknown): value is string {
return typeof value === "string";
}
// 使用示例
if (isString(someValue)) {
// `someValue` 现在的类型是 `string`
}
6. 明确声明函数返回类型
始终指定函数的返回类型,以避免意外的 any 推断。
function getUser(): User {
// implementation…
return { id: 1, name: "Alice", email: "alice@example.com" };
}
7. 使用枚举定义固定值集合
枚举使代码更易读,并且比魔法字符串或数字更能避免拼写错误。
enum Role {
Admin = "ADMIN",
User = "USER",
}
8. 使用泛型编写可复用代码
泛型让你创建灵活且类型安全的抽象。
function identity(value: T): T {
return value;
}
// 示例
const num = identity(42);
const str = identity("hello");
9. 验证外部数据
永远不要盲目相信外部数据;为 API 响应定义明确的结构。
interface ApiResponse {
success: boolean;
data: User[];
}
10. 信任 TypeScript 的推断引擎
TypeScript 通常能够正确推断类型,减少样板代码的同时保持安全性。
const users = [] as User[]; // inferred as User[]
结束语
TypeScript 并不是让你写更多代码,而是让你写出更安全、更智能、更可预测的代码,节省大量调试时间,同时保持代码库的整洁和可维护性。