TypeScript 中 type 和 interface 的用法和区别 超详细 超详细 !!~~
·
1. type(类型别名)
基本用法
// 1 基本类型别名
type Name = string
type Age = number
// 2 对象类型
type User = {
id: number;
name: string;
email: string;
}
// 3 联合类型
type Status = 'success' | 'error' | 'pending';
type Id = 'number' | 'string';
// 4 交叉类型
type Person = {
name: string;
age: number;
type Employee = Person & {
employeeId: number;
department: string;
}
高级用法
// 条件类型
type IsString<T> = T extends string ? true : false;
type Result1 = IsString<'hello'>; // true
type Result2 = IsString<123>; // false
// 映射类型
type Optional<T> = {
[P in keyof T]?: T[P];
};
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
// 模板字面量类型
type EventName = 'click' | 'hover' | 'focus';
type HandlerName = `on${Capitalize<EventName>}`; // "onClick" | "onHover" | "onFocus"
2. interface(接口)
// 基本用法
// 对象接口
interface User {
id: number;
name: string;
email: string;
}
// 可选属性
interface Config {
url: string;
timeout?: number;
retry?: boolean;
}
// 只读属性
interface Point {
readonly x: number;
readonly y: number;
}
// 函数接口
interface SearchFunc {
(source: string, subString: string): boolean;
}
// 可索引接口
interface StringArray {
[index: number]: string;
}
继承和扩展 (extends)
// 接口继承
interface Person {
name: string;
age: number;
}
interface Employee extends Person {
employeeId: number;
department: string;
}
// 合并声明(声明合并)
interface User {
name: string;
}
interface User {
age: number;
}
// 最终 User 接口包含 name 和 age
const user: User = {
name: 'John',
age: 30
};
3. type 和 interface 的区别
**主要区别对比**
特性 type(类型别名) interface(接口)
声明合并 ❌ 不支持 ✅ 支持
扩展方式 交叉类型(&) extends 关键字
实现类 ❌ 不能 ✅ 可以被类实现
性能 稍好(无声明合并检查) 稍差(需要检查声明合并)
适用场景 复杂类型、联合类型、元组等 对象形状、类实现、API 定义
## 具体示例
1. 扩展方式不同
typescript
// interface 使用 extends
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
// type 使用交叉类型 &
type Animal = {
name: string;
};
type Dog = Animal & {
breed: string;
};
2. 声明合并
typescript
// interface 支持声明合并
interface User {
name: string;
}
interface User {
age: number;
}
// 最终 User 包含 name 和 age
const user: User = {
name: 'John',
age: 30
};
// type 不支持声明合并,会报错
type User = {
name: string;
};
type User = { // Error: 重复标识符 'User'
age: number;
};
3. 类实现
typescript
// interface 可以被类实现
interface Serializable {
serialize(): string;
}
class User implements Serializable {
constructor(public name: string, public age: number) {}
serialize(): string {
return JSON.stringify(this);
}
}
// type 不能直接被类实现(但可以间接实现)
type Serializable = {
serialize(): string;
};
// 这样会报错
class User implements Serializable { // Error!
// ...
}
4. 使用建议
推荐使用 interface 的情况
typescript
// 1. 定义对象形状,特别是需要被实现的
interface ComponentProps {
title: string;
onClick: () => void;
}
// 2. 需要声明合并的库类型定义
interface Window {
myCustomProperty: string;
}
// 3. 面向对象编程,类需要实现的契约
interface Repository<T> {
findById(id: number): T | undefined;
save(entity: T): void;
}
推荐使用 type 的情况
typescript
// 1. 联合类型
type Status = 'loading' | 'success' | 'error';
type Action = { type: 'ADD' } | { type: 'REMOVE' };
// 2. 元组类型
type Point = [number, number];
type Data = [string, number, boolean];
// 3. 复杂映射类型
type Partial<T> = {
[P in keyof T]?: T[P];
};
// 4. 函数类型
type ClickHandler = (event: MouseEvent) => void;
// 5. 从其他类型组合
type UserProfile = Pick<User, 'name' | 'email'>;
5. 实际应用示例
typescript
// 综合使用示例
interface BaseEntity {
id: number;
createdAt: Date;
updatedAt: Date;
}
type Status = 'active' | 'inactive' | 'pending';
interface User extends BaseEntity {
name: string;
email: string;
status: Status;
}
// 使用 type 创建工具类型
type UserWithoutTimestamps = Omit<User, 'createdAt' | 'updatedAt'>;
type UserCreateInput = Pick<User, 'name' | 'email'>;
// 函数重载
interface ApiClient {
get(url: string): Promise<Response>;
post(url: string, data: any): Promise<Response>;
}
// 条件类型
type ApiResponse<T> = {
data: T;
success: true;
} | {
error: string;
success: false;
};
type UserResponse = ApiResponse<User>;
3. enum(Enum用于定义命名常量集合, enum通过enum关键字定义一组相关常量,增强代码可读性和安全性)
enum Direction {
Up = "up",
Down = "down",
Left = "left",
Right = "right"
}
### 总结
interface 更适合面向对象编程,支持声明合并和类实现
type 更适合函数类型、联合类型、元组和复杂类型操作
在大多数对象形状定义中,两者可以互换,根据团队规范选择
保持一致性:在项目中统一使用一种方式,或者根据具体场景选择最合适的
选择建议:优先使用 interface 直到需要 type 的特定功能。
更多推荐

所有评论(0)