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 可以定义联合类型、交叉类型等复杂类型,为开发者提供极大的灵活性。
相关推荐
未济3 天前
linux 配置环境变量
linux
傲世仙尊3 天前
目录即文件-Ext文件系统收尾篇
linux·c语言
_艾伦 耶格尔.3 天前
进程间通信
linux
Liuqy-053 天前
Linux IO编程——静态库、动态库
linux
彧azz3 天前
Linux 环境下 Redis 学习总结:数据类型、持久化、锁、事务、主从与缓存问题
linux·redis·笔记·学习·面试
-梅4 天前
linux(8) 软硬链接
linux·运维·服务器
AIgorithmGEEK4 天前
[Linux]线程三部曲(上):一个执行流的诞生——从操作系统一路拆到 pthread_create
linux·线程·pid
琥珀色糖4 天前
SimlpeHttp
linux·服务器
qeen874 天前
【Linux】操作系统之进程介绍(二)
linux·笔记·学习·进程
Zenova EdgeOS4 天前
Linux ss 工业边缘网络分析实战
linux·python·边缘计算·工业网关