当前位置: 首页 > news >正文

实用指南:Typescript高级类型详解

实用指南:Typescript高级类型详解

Typescript中的高级类型主要有下面几种:

1. 联合类型 (Union Types)

type Status = "success" | "error" | "loading";
type ID = string | number;
function handleStatus(status: Status) {// status 只能是 "success", "error", "loading" 之一
}

2. 交叉类型 (Intersection Types)

interface Person {name: string;age: number;
}
interface Employee {employeeId: string;department: string;
}
type Staff = Person & Employee;
// Staff 必须同时包含 Person 和 Employee 的所有属性

3. 映射类型 (Mapped Types)

// 将所有属性变为可选
type Partial = {[P in keyof T]?: T[P];
};
// 将所有属性变为只读
type Readonly = {readonly [P in keyof T]: T[P];
};
interface User {id: number;name: string;
}
type PartialUser = Partial; // { id?: number; name?: string; }

4. 条件类型 (Conditional Types)

type IsString = T extends string ? true : false;
type A = IsString; // true
type B = IsString; // false
// 内置示例
type Exclude = T extends U ? never : T;
type Extract = T extends U ? T : never;

5. 索引访问类型 (Indexed Access Types)

interface User {id: number;name: string;address: {street: string;city: string;};
}
type UserName = User["name"]; // string
type Address = User["address"]; // { street: string; city: string; }
type UserProperties = User[keyof User]; // string | number | { street: string; city: string; }

6. 模板字面量类型 (Template Literal Types)

type EventName = "click" | "hover" | "focus";
type HandlerName = `on${Capitalize}`;
// "onClick" | "onHover" | "onFocus"
type CSSValue = `${number}px` | `${number}em` | `${number}%`;

7. 递归类型 (Recursive Types)

type Json =| string| number| boolean| null| { [key: string]: Json }| Json[];
type DeepReadonly = {readonly [P in keyof T]: T[P] extends object? DeepReadonly: T[P];
};

区别与联系

区别

类型主要用途特点
联合类型表示多个类型之一使用 `` 运算符
交叉类型合并多个类型使用 & 运算符
映射类型批量转换属性使用 in 关键字
条件类型基于条件选择类型使用三元运算符
索引访问获取特定属性类型使用 [] 语法
模板字面量字符串模式匹配使用模板字符串语法

联系与组合使用

这些高级类型经常组合使用,形成强大的类型编程能力:

// 组合使用示例
interface Product {id: number;name: string;price: number;category: "electronics" | "clothing" | "books";
}
// 获取所有字符串属性的键
type StringKeys = {[K in keyof T]: T[K] extends string ? K : never;
}[keyof T];
type ProductStringKeys = StringKeys; // "name" | "category"
// 创建动态的 getter 类型
type Getters = {[K in keyof T as `get${Capitalize}`]: () => T[K];
};
type ProductGetters = Getters;
// {
//   getId: () => number;
//   getName: () => string;
//   getPrice: () => number;
//   getCategory: () => "electronics" | "clothing" | "books";
// }

这些高级类型让 TypeScript 的类型系统变得极其强大,能够精确地描述复杂的类型关系,提供更好的类型安全和开发体验。

http://www.hskmm.com/?act=detail&tid=24291

相关文章:

  • 集合幂级数,FMT 与 FWT 学习笔记
  • 2025多校CSP模拟赛1
  • 上传文件前端需要注意的三个点:
  • AT_arc189_b [ARC189B] Minimize Sum
  • Jenkins安装与配备
  • 2025-10-04 60S读世界
  • 适合新手的PPT模板网站,简单操作但效果好!
  • 2025多校冲刺CSP模拟赛2 总结
  • pip list 可以查到某个包,但是,import某个包,出现 ModuleNotFoundError: No module named
  • 详细介绍:conda使用指南
  • 探索 Docker/K8s 部署 MySQL 的创新实践与优化技巧 - 详解
  • 基于Registry搭建docker加速镜像服务
  • mssql 无锁读取
  • 2025年四川大学计算机学院专硕考研经验分享
  • 基础数学拾遗
  • 2025多校冲刺CSP模拟赛2(普通的颓唐)
  • 模板大全
  • springCloudMaven打包配置 - br
  • springCloud打包时根目录配置和公共包打包配置 - br
  • 2025.10.4 - 10.17
  • 题解:P5504 [JSOI2011] 柠檬
  • Thymeleaf教程
  • Vmware虚拟机设置中处理器数量和内核内存再次探讨
  • VMware中Ubuntu迁移(复制)后进入紧急模式You are in emergency mode.
  • 太简单了!原来PS在线抠图可以这么玩,背景分离无压力
  • 深入解析:【Leetcode】随笔
  • 实用指南:Linux驱动之V4L2
  • 儿童与青少年数据安全及体育发展新方向会议
  • 威联通NAS Emby-Server 的SQLite数据库损坏和程序损坏修复
  • Embarcadero Dev-C++ 6.3 中文乱码问题 - 教程