TypeScript - type

在 TypeScript 中,type 关键字用于定义类型别名,即为一个类型创建新的名字。这种类型别名可以用于基本类型、联合类型、交叉类型、对象类型、函数类型等多种类型结构。

一.基本语法

bash 复制代码
type NewTypeName = ExistingType;

二.常见使用场景

  • 1.基本类型别名 给已有类型起一个新的名字,方便后续使用。
bash 复制代码
type ID = number;
let userId: ID = 123;
  • 2.联合类型 可以将多个类型组合在一起。
bash 复制代码
type Status = 'success' | 'error' | 'loading';

let requestStatus: Status;
requestStatus = 'success';  // 合法
requestStatus = 'failed';   // 错误,不在 'success' | 'error' | 'loading' 之中
  • 3.对象类型 定义一个对象的结构。
bash 复制代码
type User = {
  id: number;
  name: string;
  age?: number;  // 可选属性
};

const user: User = {
  id: 1,
  name: 'Alice',
};
  • 4.函数类型 定义一个函数的签名。
bash 复制代码
type Add = (a: number, b: number) => number;

const add: Add = (x, y) => x + y;
  • 5.交叉类型 可以将多个类型合并在一起,使得变量同时满足多个类型。
bash 复制代码
type Person = {
  name: string;
  age: number;
};

type Employee = {
  employeeId: number;
  department: string;
};

type Staff = Person & Employee;

const staffMember: Staff = {
  name: 'Bob',
  age: 30,
  employeeId: 12345,
  department: 'IT'
};
  • 6.复杂类型组合 可以通过 type 定义更复杂的类型结构,包括数组、元组等。
bash 复制代码
type Point = [number, number];  // 元组
let p1: Point = [0, 0];

type StringArray = string[];  // 字符串数组
let names: StringArray = ['Alice', 'Bob'];

三.使用 type 的好处

  • 可读性和复用性:通过类型别名,你可以给复杂的类型起一个简单的名字,使代码更容易理解和复用。
  • 类型安全:你可以确保值符合特定的类型,防止意外的类型错误。
  • 灵活性:type 可以定义联合类型、交叉类型等复杂类型,为开发者提供极大的灵活性。
相关推荐
orion5717 小时前
Missing Semester Class1:course overview and introduction of shell
linux
用户120487221611 天前
Linux驱动编译与加载
linux·嵌入式
ch_09181 天前
从0构建SDK第3节:实现 ReActAgent 的推理与行动循环
typescript·llm·agent
疯狂的魔鬼1 天前
一套 Schema 驱动四视图:记 useCrudSchemas 的设计与实践
前端·javascript·typescript
用户805533698031 天前
Input 子系统架构:Core、Handler、Driver 三层是怎么协作的
linux·嵌入式
用户805533698031 天前
RK-Forge外设系列开篇 - 把板子从「能启动」变成「能用」:Ethernet/SPI/MMC 三个纯接线外设
linux·github·嵌入式
七歌杜金房2 天前
我终于又有了自己的 Linux 电脑
linux·debian·mac
tntxia3 天前
linux curl命令详解_curl详解
linux
扛枪的书生3 天前
Linux 网络管理器用法速查
linux
顺风尿一寸3 天前
Java Socket 内核之旅:从 SocketChannel.read() 到 tcp_recvmsg 与 epoll 的完整调用链路
linux