前言
这篇文章诞生的契机来自于写项目中,发现type和interface的功能似乎重合,于是网上搜索一番,发现官网早有了解释,感兴趣的同学可以去官网查看一番www.typescriptlang.org, 这里做个简单的翻译好了。
Type Aliases和interface的区别
Type aliases和interface非常相似,在多数情况下你可以任选其一。 interface的几乎所有的功能都可以在type中实现,唯一的不同就是使用type声明的类型不能添加新的属性而interface声明的类型是可以扩展的。
代码:
//使用interface声明的类型后再添加新的属性,运行成功
interface Window {
title: string
}
interface Window {
ts: TypeScriptAPI
}
const src = 'const a = "Hello World"';
window.ts.transpileModule(src, {});
//使用type声明的类型再添加新的属性,运行失败
type Window = {
title: string
}
type Window = {
ts: TypeScriptAPI
}
// Error: Duplicate identifier 'Window'.
interface和type继承声明的用法
如果非要在type之后添加新的属性,可以使用下面这种继承声明的用法。
代码:
//Extending a type via intersections
type Animal = {
name: string
}
type Bear = Animal & {
honey: boolean
}
const bear = getBear();
bear.name;
bear.honey;
//Extending an interface
interface Animal {
name: string
}
interface Bear extends Animal {
honey: boolean
}
const bear = getBear()
bear.name
bear.honey