interface 和 type 的使用场景有什么区别?

Typescript 提供的核心特性之一,旨在编译时期补货并防止类型相关的错误,从而提高代码质量,使其更可靠更易维护。

变量类型的注解

// 指定变量的类型,变量只能存储特定类型的值
let s: string = 'abc';
let n: number = 123;
let i: boolean = false;

函数参数和返回值的类型注解

// 在函数中指定参数和返回值的类型
function add(n1: number, n2: number): number {
  return n1 + n2;
}

接口(interface)和类型别名(Type Aliases)

优先使用 interface 的场景
  1. 用于定义对象结构的类型
// 定义对象形状
interface Animal {
  name: string;
  eat(food: string): void;
}

class Dog implements Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  eat(food: string) {
    console.log(`${this.name} eats ${food}`);
  }
}
  1. 需要声明合并
// 扩展第三方库或已有类型:
interface Window {
  myCustomProp: string; // 扩展全局 Window 类型
}
  1. 面向对象设计
// 使用继承构建类型层次结构:
interface Shape {
  color: string;
}

interface Circle extends Shape {
  radius: number;
}
优先使用 type 的场景
  1. 定义复杂类型
// 联合类型、交叉类型、元组等:
type ID = string | number;
type Coordinates = [number, number];
type StringOrNumberArray = Array<string | number>;
  1. 类型操作
// 使用映射类型、条件类型等高级特性:
type Readonly<T> = {
  readonly [K in keyof T]: T[K];
};

type Optional<T> = {
  [K in keyof T]?: T[K];
};
  1. 类型别名
// 简化复杂类型,提高可读性:
type User = {
  id: string;
  name: string;
  email: string;
};

function createUser(user: User) { /* ... */ }
兼容性和替代性
  • 大部分情况下,两者可以互换使用:
interface Point { x: number; y: number }
type PointType = { x: number; y: number };

let p1: Point = { x: 1, y: 2 };     // 正确
let p2: PointType = { x: 1, y: 2 }; // 正确
  • 两者都可以被工具类型操作
type PartialPoint = Partial<Point>;
interface PartialPointInterface extends Partial<Point> {}
最佳实践

默认情况下优先使用 interface(在定义对象、类实现、可能有扩展需求的场景下优先选择 interface)
复杂类型用 type(涉及联合、元组、交叉或者有类型操作的场景)

总结

interface:适合定义对象结构、类契约、可扩展类型
type:适合复杂类型、类型操作和别名

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值