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

interface X {
    a: number
    b: string
}

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

当前回答

除了已经提供的出色答案之外,在扩展类型和接口方面还有明显的区别。我最近遇到了一些界面无法完成任务的情况:

无法使用接口扩展联合类型无法扩展通用接口

其他回答

TypeScript手册给出了答案:

界面的几乎所有功能都是可用的类型。关键区别在于不能重新打开类型以添加新的财产vs始终可扩展的接口。

想加上我的2美分;

我曾经是“界面爱好者”(除了联合、交叉等以外,我更喜欢界面而不是类型)。。。直到我开始使用类型“any key value object”,即Record<string,unknown>

如果键入“任意键值对象”:

function foo(data: Record<string, unknown>): void {
  for (const [key, value] of Object.entries(data)) {
    // whatever
  }
}

如果你使用接口,你可能会走到死胡同

interface IGoo {
  iam: string;
}

function getGoo(): IGoo {
  return { iam: 'an interface' };
}

const goo = getGoo(); 

foo(goo); // ERROR
// Argument of type 'IGoo' is not assignable to parameter of type 
// 'Record<string, unknown>'.
//  Index signature for type 'string' is missing in type 
// 'IGoo'.ts(2345)

虽然打字就像一个符咒:

type Hoo = {
  iam: string;
};

function getHoo(): Hoo {
  return { iam: 'a type' }; 
}

const hoo = getHoo(); 

foo(hoo); // works

这个特定的用例——IMO——产生了不同。

在我的日常发展中,当我不知道该选择哪一个时,我会使用这个作弊表。

有关更多信息,请阅读我的博客:https://medium.com/@magenta2127/use-which-interface-or-type-alias-in-typescript-bdfaf2e882ae

还有一个不同之处。我会的。。。如果你能解释这种情况的原因,请给你买一杯啤酒:

enum Foo { a = 'a', b = 'b' }

type TFoo = {
  [k in Foo]: boolean;
}

const foo1: TFoo = { a: true, b: false} // good
// const foo2: TFoo = { a: true }       // bad: missing b
// const foo3: TFoo = { a: true, b: 0}  // bad: b is not a boolean

// So type does roughly what I'd expect and want

interface IFoo {
//  [k in Foo]: boolean;
/*
  Uncommenting the above line gives the following errors:
  A computed property name in an interface must refer to an expression whose type is a      
    literal type or a 'unique symbol' type.
  A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
  Cannot find name 'k'.
*/
}

// ???

这种情况让我很想说接口的问题,除非我有意实现一些OOP设计模式,或者需要如上所述的合并(除非我有充分的理由,否则我永远不会这么做)。

界面专门设计用于描述对象形状;然而,类型在某种程度上类似于可以用于为任何类型创建新名称的接口。

我们可以说,一个接口可以通过多次声明来扩展;而类型是封闭的。

https://itnext.io/interfaces-vs-types-in-typescript-cf5758211910