文章列表

Type & Interface

Champ2025.12.18 16:11访问量0 次阅读
Type & Interface
TS中的 类型别名 和 接口

type和interface很大程度上是一样的,用什么取决于个人偏好

// There are two main tools to declare the shape of an
// object: interfaces and type aliases.
//
// They are very similar, and for the most common cases
// act the same.

type BirdType = {
  wings: 2;//指定为2不可变
  furs: number;//灵活多变
};

interface BirdInterface {
  wings: 2;
}

let bird1: BirdType = { wings: 2,furs:3333 };
let bird2: BirdInterface = {wings:2};

const bird3: BirdInterface = bird1;//多的可以赋值给少的

// Type通过 & 扩展
type Owl = { nocturnal: true } & BirdType;
type Robin = { nocturnal: false } & BirdInterface;

// interfaces 通过 ”extend“ 扩展
interface Peacock extends BirdType {
  colourful: true;
  flies: false;
}
interface Chicken extends BirdInterface {
  colourful: false;
  flies: false;
}

let owl: Owl = { wings: 2, nocturnal: true,furs: 33332 };
let chicken: Chicken = { wings: 2, colourful: false, flies: false };

//官方推荐使用interface,因为interface报错显示更加详细,更易于debug
owl = chicken;//报错
chicken = owl;

//另外一个主要区别是,type是封闭的,interface是开放的,意味着interface可以重新再定义以扩展
interface Kitten {
  purrs: boolean;
}

interface Kitten {
  colour: string;
}

const cat:Kitten = {purrs:true,colour:'123'}

//而type不可重定义
type Puppy = {
  color: string;
};

type Puppy = {//报错
  toys: number;
};

// Depending on your goals, this difference could be a
// positive or a negative. However for publicly exposed
// types, it's a better call to make them an interface.

// One of the best resources for seeing all of the edge
// cases around types vs interfaces, this stack overflow
// thread is a good place to start:

// https://stackoverflow.com/questions/37233735/typescript-interfaces-vs-types/52682220#52682220

历史留言 (0)
ICP备案号浙ICP备2026065730号-1公安备案号浙公网安备33019202003213号