interface
你可以在任何时候用interfaces取代types
type Article = {title: string,price: number,vat: number,stock?: number,description?: string}interface ShopItem {title: string;price: number;vat: number;stock?: number;description?: string;}
Article和ShopItem具有相同的结构, interface各项间用分号隔开,也可以没有分号
如果使用class, types和interfaces都能被implemented
class DVD implements ShopItem {title: stringprice: numbervat: numberconstructor(title: string) {this.title = titlethis.price = 9.99this.vat = 0.2}}class Book implements Article {title: stringprice: numbervat: numberconstructor(title: string) {this.title = titlethis.price = 39this.vat = 0.2}}
这里Book和DVD有相同的结构
Declaration Merging
interface和type最大的区别,是interface支持declaration merging
这意味着我们可以在同一个文件的不同位置声明同一个interface,TypeScript会把这些声明合并成一个
例如,在上述代码的基础上我们再加一段
interface ShopItem {reviews: {rating: number,content: string}[]}
typescript会将刚开始声明的ShopItem和我们新增的合并
而使用了ShopItem接口的DVD类声明则会报错,因为缺少了新增的reviews属性
interface的这个特性适用于扩充全局interface,比如Window
declare global {interface Window {isDevelopment: boolean}}
我们首先打开gloabl命名空间(namespace), namespace也可以被merge
然后打开Window接口,添加新的isDevelopment属性
然后我们就可以在任何地方使用window对象的这个新属性
class Discount {...apply(article: Article) {...// Here we check if we are in dev modeif(window.isDevelopment) {console.log('Another discount applied')}}}
