ts:接口vs类型别名

101 阅读1分钟

产生原因:我们想多次使用同一个类型,并用一个名称引用他。 就可以使用类型别名/接口。

类型别名:
type Point = {
    x:number;
    y:number;
}

function printCoord(pt: Point) {
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}
 
printCoord({ x: 100, y: 100 });
接口:

是命名对象类型的另外一种方式

interface Point {
  x: number;
  y: number;
}
 
function printCoord(pt: Point) {
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}
 
printCoord({ x: 100, y: 100 });
区别

类型别名和接口是十分相似的,大多数情况下你可以随意选择。但是接口是比类型别名的功能更加强大。接口不仅具备类别别名所具有的所有功能,还具备扩展的功能,可以重新打开类型来添加属性。

1.二者都可以扩展接口

interface Animal {
  name: string
}

interface Bear extends Animal {
  honey: boolean
}

const bear = getBear() 
bear.name
bear.honey
type Animal = {
  name: string
}

type Bear = Animal & { 
  honey: boolean 
}

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

2.接口可以添加新的属性,类型别名不行

interface Window {
  title: string
}

interface Window {
  ts: TypeScriptAPI
}

const src = 'const a = "Hello World"';
window.ts.transpileModule(src, {});
type Window = {
  title: string
}

type Window = {
  ts: TypeScriptAPI
}

 // Error: Duplicate identifier 'Window'.

3.接口不能命名为原语 (原语:数据类型 string number等)