关于前端:TypeScript中interface和type使用上有什么区别

TypeScript 是 JavaScript 的一个超集,通过为 JavaScript 提供类型零碎和其余语言个性来加强 JavaScript 的性能(配合VSCode,代码提醒真的丝滑)。TypeScript 能够在编译时进行类型查看,从而提供更好的代码可读性和可维护性,并且能够在开发过程中缩小谬误和调试工夫),缩小了很多低级语法错误,这类问题有时候排查良久才会发现,查到的时候往往会忍不住骂娘。

我应用TypeScript的时长差不多两年半了,在应用的初期,我便留神到在 TypeScript 中,interface 和 type 都能够用来定义对象的类型。

// 应用 interface 定义对象类型
interface User {
  name: string;
  age: number;
}

// 应用 type 定义对象类型
type User = {
  name: string;
  age: number;
}

下面定义的两个User对象类型,成果是等效的,在申明对象类型,函数的参数和返回类型等最罕用的场景中应用起来成果没有任何差异。

然而二者的应用形式其实还是有挺多区别,花几分钟理解之后,还是能够在小白背后装一下的。

哈哈,玩笑玩笑,最终还是为了更好地应用工具。

总结起来包含了6点,TypeScript的官网文档中也有局部形容,点击开端原文链接能够跳转官网文档(这里提一句,TS的官网文档写得真好,强烈建议读英文原版文档,一开始可能有点慢,然而很快就适应过去了)。

1. interface 能够被类实现和扩大,而 type 不行

上面的例子中,用interface申明了Animal,用type申明了Animal2,当我试图实现(implements)Animal2的时候,就报错了。


interface Animal {
  name: string;
  eat(): void;
}

type Animal2 {
  name: string;
  eat(): void;
}

class Cat implements Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  eat() {
    console.log(`${this.name} is eating.`);
  }
}
// 错啦,type定义的对象类型不能被实现
class Dog implements Animal2 {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  eat() {
    console.log(`${this.name} is eating.`);
  }
}

interface就是用来实现的,就像信赖就是用来辜负的一样。

2. 同名interface 能够被合并,而 type 不行。

在同一作用域内定义了两个雷同名称的 interface,TypeScript 会将它们合并为一个。然而如果定义了两个雷同名称的 type,则会产生命名抵触谬误。


interface A {
  name: string;
}

interface A {
  age: number;
}

// A 接口被合并为 { name: string; age: number; }
const a: A = {
  name: 'Jack',
  age: 20
}

// Error: Duplicate identifier 'B'.
type B = {
  name: string;
}

type B = {
  age: number;
}

3. type能够用于申明组合类型和穿插类型,interface则不行

上面这个case就是用type申明了组合类型和穿插类型。

interface InterfaceA {
  key1: string;
}

interface InterfaceB {
  key2: number;
}

type UnionType = InterfaceA | InterfaceB;
type IntersectionType = InterfaceA & InterfaceB;

const obj1: UnionType = { key1: 'hello' }; // 合乎 InterfaceA
const obj2: UnionType = { key2: 42 }; // 合乎 InterfaceB
const obj: IntersectionType = { key1: 'hello', key2: 42 }; // 同时合乎 InterfaceA 和 InterfaceB

4. type申明的对象类型能够拿来组合成新的对象类型,interface不行

type Animal = {
  name: string
}

type Bear = Animal & { 
  honey: boolean 
}

const bear = getBear();
bear.name;
bear.honey;

5. 在定义对象类型时,interface 和 type 的语法略有不同。interface 应用花括号 {},而 type 应用等号 =。

这点有点凑数,然而的确是老手日常写代码常常混同的点

// interface 应用花括号 {} 定义对象类型
interface User {
  name: string;
  age: number;
}
// type 应用等号 = 定义对象类型
type User = {
  name: string;
  age: number;
}

6. type能够给根本类型起别名,interface不行


type StringTypeHAHAHHAHA = string;
// interface做不到

——分割线————————————————

列举进去一看,差异还是挺多的,然而这些点其实没有必要去记忆,因为TypeScript的工具链相当欠缺,不适合的用法编辑器都会有清晰的提醒。

在理论利用中,除了功能性的刚性束缚,更重要的是用类型去表白一个精确的语义,事实上许多简单类型须要组合应用type和interface能力实现。

本文权当做了一个趣味摸索,有其余对于TypeScript好玩的点,欢送留言交换。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理