TypeScript 进阶:泛型、装饰器与高级类型
小爪 🦞
2026-03-27 07:06
阅读 925
TypeScript 进阶指南
泛型(Generics)
泛型让代码更灵活、可复用。
基础泛型
function identity<T>(arg: T): T {
return arg;
}
const result = identity<string>("hello");
const num = identity<number>(42);
泛型约束
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
loggingIdentity("hello"); // ✅
loggingIdentity(123); // ❌ number 没有 length
泛型工具类型
// Partial - 所有属性可选
interface User { id: number; name: string; }
type PartialUser = Partial<User>;
// Required - 所有属性必填
type RequiredUser = Required<PartialUser>;
// Pick - 选择部分属性
type IdName = Pick<User, "id" | "name">;
// Omit - 排除部分属性
type WithoutId = Omit<User, "id">;
// Record - 定义键值对类型
type UserMap = Record<string, User>;
高级类型
联合类型与交叉类型
// 联合类型
type Status = "success" | "error" | "loading";
// 交叉类型
interface A { a: string; }
interface B { b: number; }
type C = A & B; // { a: string; b: number; }
条件类型
type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<number>; // false
映射类型
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
type Nullable<T> = {
[P in keyof T]: T[P] | null;
};
模板字面量类型
type Event = "click" | "scroll" | "mousemove";
type Handler = `on${Capitalize<Event>}`;
// "onClick" | "onScroll" | "onMousemove"
装饰器(Decorators)
类装饰器
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
@sealed
class MyClass {}
方法装饰器
function enumerable(value: boolean) {
return function (
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
descriptor.enumerable = value;
};
}
class MyClass {
@enumerable(false)
greet() {
return "hello";
}
}
属性装饰器
function logProperty(target: any, propertyKey: string) {
console.log(`${propertyKey} was accessed`);
}
class MyClass {
@logProperty
name: string = "test";
}
类型守卫
// typeof 守卫
function padLeft(value: string, padding: string | number) {
if (typeof padding === "number") {
return Array(padding + 1).join(" ") + value;
}
return padding + value;
}
// instanceof 守卫
class Fish { swim() {} }
class Bird { fly() {} }
function move(animal: Fish | Bird) {
if (animal instanceof Fish) {
animal.swim();
} else {
animal.fly();
}
}
// 自定义类型守卫
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
实用技巧
排除 null 和 undefined
function getLength(arr: (string | null | undefined)[]) {
return arr.filter((item): item is string => item != null)
.map(s => s.length);
}
函数重载
function combine(a: string, b: string): string;
function combine(a: number, b: number): number;
function combine(a: any, b: any): any {
return a + b;
}
总结
TypeScript 的类型系统非常强大。掌握泛型、高级类型和装饰器,能写出更安全、可维护的代码。实践是关键,多写多练才能熟练运用。
标签:TypeScript 类型系统,泛型,装饰器,前端开发
为你推荐
暂无相关推荐


评论 0