TypeScript中的这些语句(接口与类型)有什么区别?

interface X {
    a: number
    b: string
}

type X = {
    a: number
    b: string
};

当前回答

文件已经解释了

一个区别是,接口创建了一个新名称,该名称在任何地方都可以使用。类型别名不会创建新名称-例如,错误消息不会使用别名名称。在旧版本的TypeScript中,类型别名无法从扩展或实现(也无法扩展/实现其他类型)。从2.7版起,可以通过创建新的交叉点类型来扩展类型别名另一方面,如果不能用接口表达某种形状,并且需要使用联合或元组类型,则通常使用类型别名。

接口与类型别名

其他回答

接口与类型

接口和类型用于描述对象和原语的类型。接口和类型通常可以互换使用,并且通常提供类似的功能。通常由程序员选择自己的偏好。

然而,接口只能描述创建这些对象的对象和类。因此,必须使用类型来描述字符串和数字等原语。

下面是接口和类型之间的两个区别的示例:

// 1. Declaration merging (interface only)

// This is an extern dependency which we import an object of
interface externDependency { x: number, y: number; }
// When we import it, we might want to extend the interface, e.g. z:number
// We can use declaration merging to define the interface multiple times
// The declarations will be merged and become a single interface
interface externDependency { z: number; }
const dependency: externDependency = {x:1, y:2, z:3}

// 2. union types with primitives (type only)

type foo = {x:number}
type bar = { y: number }
type baz = string | boolean;

type foobarbaz = foo | bar | baz; // either foo, bar, or baz type

// instances of type foobarbaz can be objects (foo, bar) or primitives (baz)
const instance1: foobarbaz = {y:1} 
const instance2: foobarbaz = {x:1} 
const instance3: foobarbaz = true 

“typescriptlang”似乎建议尽可能使用接口而不是类型。接口与类型别名

2021 3月更新:更新的TypeScript手册(也在nju-clc中提到下面的答案)有一节“接口与类型别名”,解释了区别。


原始答案(2016)

根据(现已存档)TypeScript语言规范:

与总是引入命名对象类型的接口声明不同,类型别名声明可以引入任何类型的名称,包括基元类型、联合类型和交集类型。

该规范还提到:

接口类型与对象类型的类型别名有许多相似之处但是由于接口类型提供了更多的功能通常优选键入别名。例如,接口类型接口点{x: 数量;y: 数量;}可以写成类型别名类型点={x: 数量;y: 数量;};但是,这样做意味着失去以下功能:接口可以在extends或implements子句中命名,但对象类型文本的类型别名不能在TS 2.7之后为true。接口可以有多个合并声明,但对象类型文本的类型别名不能。

文档中指出的关键区别在于,可以重新打开接口以添加新属性,但不能重新打开类型别名以添加新的属性,例如:

这没问题

interface x {
  name: string
}

interface x {
  age: number
}

这将抛出错误Duplicate identifier y

type y = {
  name: string
}

type y = {
  age: number
}

除此之外,接口和类型别名类似。

https://www.typescriptlang.org/docs/handbook/advanced-types.html

一个区别是,接口创建了一个新名称,该名称在任何地方都可以使用。键入别名不会创建新名称-例如,错误消息不会使用别名。