返回首页

TypeScript 实用技巧分享

·2 min read
TypeScript前端技巧


TypeScript 实用技巧

TypeScript 为 JavaScript 添加了类型系统,让我们的代码更加健壮。这里分享一些实用的技巧。

1. 类型推断

TypeScript 有强大的类型推断能力,很多时候不需要显式声明类型:

// 不需要这样写
const name: string = "Hello";

// TypeScript 会自动推断
const name = "Hello"; // 类型是 string

2. 联合类型和类型守卫

type Status = "loading" | "success" | "error";

function handleStatus(status: Status) {
switch (status) {
case "loading":
return "加载中...";
case "success":
return "成功!";
case "error":
return "出错了";
}
}

3. 泛型的使用

泛型让我们可以编写可重用的组件:

function getFirst<T>(arr: T[]): T | undefined {
return arr[0];
}

const firstNumber = getFirst([1, 2, 3]); // number | undefined
const firstString = getFirst(["a", "b"]); // string | undefined

4. Partial 和 Required

interface User {
name: string;
email: string;
age?: number;
}

// 所有属性变为可选
type PartialUser = Partial<User>;

// 所有属性变为必需
type RequiredUser = Required<User>;

5. 使用 as const

const colors = ["red", "green", "blue"] as const;
// 类型是 readonly ["red", "green", "blue"]

type Color = typeof colors[number];
// 类型是 "red" | "green" | "blue"

总结

TypeScript 的类型系统非常强大,善用这些技巧可以让代码更加安全和易于维护。