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 可以定义联合类型、交叉类型等复杂类型,为开发者提供极大的灵活性。
相关推荐
XH-hui1 天前
【打靶日记】THL 之 Facultad
linux·网络安全·1024程序员节·thehackerlabs
熙xi.1 天前
DHT11温湿度传感器Linux驱动开发完整流程
linux·运维·驱动开发
Yyyy4821 天前
Ubuntu部署 Kubernetes1.23
linux·运维·ubuntu
三无少女指南1 天前
在 Ubuntu 上使用 Docker 部署思源笔记:一份详尽的实践教程以及常见错误汇总
笔记·ubuntu·docker
豆约翰1 天前
xv6-riscv开发调试环境搭建(vscode+ubuntu)
ide·vscode·ubuntu
人工智能训练1 天前
在 Ubuntu 系统中利用 conda 创建虚拟环境安装 sglang 大模型引擎的完整步骤、版本查看方法、启动指令及验证方式
linux·运维·服务器·人工智能·ubuntu·conda·sglang
☆璇1 天前
【Linux】网络层协议IP
linux·服务器·tcp/ip
Xの哲學1 天前
Linux ioctl 深度剖析:从原理到实践
linux·网络·算法·架构·边缘计算
孙同学要努力1 天前
《Linux篇》进程控制——进程创建(写时拷贝)、进程终止(退出码,exit,_exit)
linux·运维·服务器
AC是你的谎言1 天前
c++仿muduo库实现高并发服务器--connection类
linux·服务器·c++·学习