TypeScript中interface和type的差别是什么?


  在TypeScript中,interface和type都是定义类型的关键字,但它们在使用和行为上存在一些差异。理解这些差异对于在合适的场景中选择正确的抽象方式至关重要。

1. interface

  interface在TypeScript中主要用于定义对象的结构,它是一种方式来告诉编译器一个对象应该具有哪些形状。

interface Person {
  name: string;
  age: number;
}

const user: Person = {
  name: "Alice",
  age: 30
};

  在这个例子中,我们定义了一个Person接口,它要求实现的对象必须有两个属性:name(字符串类型)和age(数字类型)。

2. type

  type关键字用于定义更广泛的类型,不仅仅是对象结构。它可以用来给基本类型、联合类型、元组、函数等赋予一个新名字。

type PersonType = {
  name: string;
  age: number;
};

const user: PersonType = {
  name: "Alice",
  age: 30
};

  在这个例子中,我们使用type定义了一个PersonType类型别名,它与Person接口等效。

3. interface和type的差别

3.1. 扩展性

  • interface:可以被扩展(extends),允许多个接口合并到一个接口中。
  • type:没有扩展的概念,但可以使用交叉类型(&)来组合多个类型。

3.2. 声明合并

  • interface:当有两个相同的接口声明时,它们会合并。
  • type:相同的类型别名声明会导致编译错误。

3.3. 重新声明

  • interface:可以在不同的地方重复声明同一个接口,每次声明都会为接口添加额外的成员,这被称为声明合并。
  • type:重复的类型别名声明是不允许的。

3.4. 类实现

  • interface:类可以使用implements关键字来实现接口。
  • type:不能用于类的实现。
// 使用interface
interface Person {
  name: string;
}

interface Person {
  age: number; // 这会与上面的Person接口合并
}

class User implements Person {
  name: string;
  age: number;
}

// 使用type
type PersonType = {
  name: string;
};

// 下面的声明会导致错误,因为PersonType已经被声明过了
type PersonType = {
  age: number;
};

  在这个例子中,我们展示了如何使用interface和type来定义类型,并展示了声明合并和重新声明的差异。

3.5. 基本类型别名

  • interface:不能用于基本类型的别名声明。
  • type:可以用于基本类型、联合类型、元组、函数等的别名声明。
// 使用type定义基本类型的别名
type ID = string;

const id: ID = "123"; // 使用别名ID

// 使用type定义复杂的类型别名
type User = [string, number]; // 元组类型
type Callback = () => void; // 函数类型

  在这个例子中,我们使用type来定义基本类型、元组和函数的别名

相关推荐

  1. TypeScriptinterfacetype差别什么

    2024-04-23 17:42:02       43 阅读
  2. TypeScriptinterfacetype区别

    2024-04-23 17:42:02       49 阅读
  3. GPT每日面试题-Typescripttypeinterface区别

    2024-04-23 17:42:02       36 阅读
  4. tstypeinterface类型声明区别

    2024-04-23 17:42:02       64 阅读
  5. TypeScript接口(interface )详解

    2024-04-23 17:42:02       58 阅读
  6. TypeScript“as”语法什么

    2024-04-23 17:42:02       32 阅读
  7. TypeScript interface

    2024-04-23 17:42:02       31 阅读
  8. TypeScript什么类类型接口?

    2024-04-23 17:42:02       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-23 17:42:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-23 17:42:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-23 17:42:02       82 阅读
  4. Python语言-面向对象

    2024-04-23 17:42:02       91 阅读

热门阅读

  1. conda install ensembl-vep vep -V 报错Compress/Zlib.pm

    2024-04-23 17:42:02       36 阅读
  2. android文件压缩与解压

    2024-04-23 17:42:02       41 阅读
  3. 前端汪的逆袭:从Excel表格到网页魔幻秀

    2024-04-23 17:42:02       36 阅读
  4. python常用高阶函数

    2024-04-23 17:42:02       35 阅读
  5. 管理情绪方法【你的观点“稳定”你的情绪】

    2024-04-23 17:42:02       32 阅读
  6. 富格林:戒备虚假套路保障安全

    2024-04-23 17:42:02       44 阅读
  7. C# 生成指定图片的缩略图

    2024-04-23 17:42:02       30 阅读