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

【TypeScript】类型别名(Type Alias)与接口类型(Interface)

类型别名(Type Alias)与接口类型(Interface)

🆚 核心异同点对比表

特性类型别名 (type)接口 (interface)
声明方式type Name = ...interface Name { ... }
适用类型任意类型(原始值、联合、元组等)主要对象类型
扩展方式交叉类型 &extends 继承
实现(implements)类可实现类可实现
合并声明❌ 不允许✅ 自动合并同名接口
计算属性✅ 支持❌ 不支持
映射类型✅ 支持❌ 不支持
性能更适合复杂类型操作更适合对象结构定义

🧩 相同点

1. 都可以描述对象类型

// 使用 type
type PersonT = {name: string;age: number;
};// 使用 interface
interface PersonI {name: string;age: number;
}

2. 都可以被类实现

class Student implements PersonT, PersonI {name: string;age: number;constructor(name: string, age: number) {this.name = name;this.age = age;}
}

3. 都可以扩展

// type 扩展
type EmployeeT = PersonT & { jobTitle: string };// interface 扩展
interface EmployeeI extends PersonI {jobTitle: string;
}

🎯 不同点详解

1. 类型别名更灵活

类型别名可以定义任何类型,而接口主要用于对象类型:

// 原始类型别名
type ID = string | number;// 元组类型
type Point = [number, number];// 联合类型
type Status = 'active' | 'inactive';// 这些用interface无法实现

2. 接口声明合并

接口支持自动合并,类型别名会报错:

interface User {name: string;
}interface User {age: number;
}// 最终 User 接口包含 name 和 age
const user: User = { name: 'Alice', age: 30 };// type 会报错
type UserT = { name: string };
type UserT = { age: number }; // ❌ 错误:重复标识符

3. 性能差异

  • 接口:TS 会缓存接口,检查更快
  • 类型别名:每次使用时都会重新计算,复杂类型可能影响性能

🛠️ 何时使用哪种?

使用 interface 当:

  1. 定义对象形状(尤其是需要被类实现的契约)
    interface Serializable {serialize(): string;
    }
    
  2. 需要声明合并扩展第三方类型
  3. 开发公共库的类型定义(更友好提示)

使用 type 当:

  1. 需要定义联合、交叉或元组类型
    type Result = Success | Error;
    
  2. 需要使用映射类型或条件类型
    type Nullable<T> = T | null;
    
  3. 需要定义复杂类型计算
    type KeysOfType<T, U> = {[K in keyof T]: T[K] extends U ? K : never
    }[keyof T];
    

🔧 高级技巧

1. 互相组合使用

interface Base {id: string;
}type WithTimestamps<T extends Base> = T & {createdAt: Date;updatedAt: Date;
};type User = WithTimestamps<Base>;

2. 类型提取实用类型

interface ApiResponse<T> {data: T;error: string | null;
}type ResponseData<T> = T extends ApiResponse<infer U> ? U : never;

3. 基于接口创建映射类型

interface Product {id: string;name: string;price: number;
}type ReadonlyProduct = Readonly<Product>;
type PartialProduct = Partial<Product>;
http://www.xdnf.cn/news/381745.html

相关文章:

  • Redisson 看门狗机制
  • Unity3D仿星露谷物语开发41之创建池管理器
  • 记录一次window2012r2安装配置oracle11g的过程-出现的错误以及解决方法
  • 谷歌学术链接
  • OSPF综合应用
  • Nginx高级配置
  • 解锁HBase:大数据存储的神秘之门
  • Linux:线程同步与互斥
  • 《Python星球日记》 第52天:反向传播与优化器
  • MySQL 数据类型全面指南:从理论到实践
  • HCIP笔记
  • Veins同时打开SUMO和OMNeT++的GUI界面
  • 基于Arduino Nano的DIY示波器
  • 2505d,d的借用检查器
  • 基于Spring Boot + Vue的母婴商城系统( 前后端分离)
  • InnoDB结构与表空间文件页的详解
  • 前端性能优化
  • Pycharm(二十)张量的运算与操作
  • Webug4.0靶场通关笔记-靶场搭建方法(3种方法)
  • Kubernetes生产实战(十三):灰度发布与蓝绿发布实战指南
  • 关于流媒体的知识总结
  • 全息美AISEO引领未来智能营销新趋势
  • SRP单一职责原则
  • 备战菊厂笔试3
  • short变量赋值为32768, 实际为什么是-32768?不同语言的不同进制字面量?字面量?编程语言的基本类型?
  • Java、Python、NodeJS等开发环境安装及配置镜像加速到国内源
  • .Net HttpClient 使用准则
  • 【脑机接口临床】脑机接口手术的风险?脑机接口手术的应用场景?脑机接口手术如何实现偏瘫康复?
  • RT-Thread 深入系列 Part 6:高性能与低功耗优化策略
  • 智能库室联管联控系统|智能兵器室门禁管理系统