TypeScript 类型系统进阶
TypeScript 的类型系统提供了强大的工具,帮助开发者编写更安全、更可维护的代码。除了基础类型(如 string、number、boolean),TypeScript 还支持联合类型、交叉类型、条件类型和映射类型等高级特性,进一步提升类型表达能力。
联合类型与交叉类型
联合类型(Union Types)允许变量或参数接受多种类型:
type StringOrNumber = string | number;
function logValue(value: StringOrNumber) {
console.log(value);
}
交叉类型(Intersection Types)组合多个类型为一个:
interface Person { name: string; }
interface Employee { id: number; }
type EmployeeRecord = Person & Employee;
const emp: EmployeeRecord = { name: "Alice", id: 123 };
条件类型
条件类型(Conditional Types)基于类型关系动态选择类型:
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<123>; // false
映射类型
映射类型(Mapped Types)允许基于现有类型生成新类型:
type Optional<T> = {
[P in keyof T]?: T[P];
};
interface User { name: string; age: number; }
type PartialUser = Optional<User>;
const user: PartialUser = { name: "Bob" }; // age 可选
模板字面量类型
模板字面量类型(Template Literal Types)结合字符串字面量类型,提供更精确的类型约束:
type EventName = "click" | "hover";
type HandlerName = `on${Capitalize<EventName>}`;
// "onClick" | "onHover"
类型推断与 infer
infer 关键字用于在条件类型中提取类型:
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function foo(): number { return 42; }
type FooReturn = ReturnType<typeof foo>; // number
类型守卫与自定义类型守卫
类型守卫(Type Guards)帮助缩小运行时类型范围:
function isString(value: unknown): value is string {
return typeof value === "string";
}
function process(input: unknown) {
if (isString(input)) {
console.log(input.toUpperCase()); // 类型安全
}
}
实用工具类型
TypeScript 内置了多种实用工具类型,如 Partial、Readonly、Pick 和 Omit:
interface Todo { title: string; description: string; }
type TodoPreview = Pick<Todo, "title">; // { title: string; }
type TodoInfo = Omit<Todo, "description">; // { title: string; }
通过灵活运用这些高级类型特性,可以显著提升代码的类型安全性和可维护性,减少运行时错误。
1293

被折叠的 条评论
为什么被折叠?



