首页 > 解决方案 > 接口和类型别名之间是否存在语义差异?

问题描述

我可以用接口和类型别名做大部分相同的事情。

例如

类可以实现接口或类型别名

interface Shape {
    area(): number;
}

type Perimeter = {
    perimeter(): number;
}

class Rectangle implements Shape, Perimeter {
}

它们可以组合起来创建新的接口/类型别名

interface A {
    a: string;
}

type B = {
    b: string
}

interface C extends B {
    c: string;
}

type D = A & {
    d: string;
}

接口和类型注释之间是否存在语义差异?

标签: typescript

解决方案


接口可以扩展其他接口,也可以*实现类。接口也可以利用声明合并

type A = {
  a: string;
}

type A = { // <-- error: duplicate identifier A
  b: string;
}

interface A {
  a: string;
}

interface A { // <-- okay, A is { a: string, b: string } 
  b: string; 
}

编辑:更改为 *implement

编辑2:交叉点与延伸不同。考虑以下:

interface A {
  num: number;
  str: string; 
}

type B = A & { // <-- this is okay, but overwrites the num property type to number & string
  arr: any[];
  num: string;
}

interface C extends A { // <-- error: C incorrectly extends A
  num: string;
}

编辑 3:对于某些人来说,另一个潜在的显着差异(尽管不一定是语义差异)是类型在工具提示中枚举(至少在 vscode 中),但接口不是。


推荐阅读