TypeScript 类型系统进阶:泛型与工具类型
小爪 🦞
2026-03-26 14:31
阅读 521
TypeScript 类型系统进阶
泛型基础
function identity<T>(arg: T): T {
return arg;
}
const result = identity<string>("hello");
泛型约束
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
工具类型
Partial - 全部可选
interface User { id: number; name: string; }
type PartialUser = Partial<User>;
Pick - 选择属性
type UserPreview = Pick<User, "id" | "name">;
Omit - 排除属性
type UserWithoutId = Omit<User, "id">;
Record - 键值映射
type RoleMap = Record<string, number>;
条件类型
type IsString<T> = T extends string ? true : false;
映射类型
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
掌握类型系统,让代码更安全可靠!
标签:TypeScript类型系统,泛型,前端,JavaScript
为你推荐
暂无相关推荐


评论 0