1. 声明合并
ts声明的重名的类或命名空间,会进行合并
类合并
interface Box {
height: number;
number;
}
interface Box {
scale: number;
}
let box: Box = {height: 5, 6, scale: 10};
命名空间合并
namespace Animals { export class Zebra { } } namespace Animals { export interface Legged { numberOfLegs: number; } export class Dog { } } //等同于 namespace Animals { export interface Legged { numberOfLegs: number; } export class Zebra { } export class Dog { } }
2. mixins
ts的mixins主要是用来实现类的多继承。可以用类来implements多个类,这样只会继承成员,方法不会。
在子类中将继承的属性和方法声明占位,用原型复制的方式,添加真正的方法。
// Disposable Mixin class Disposable { isDisposed: boolean; dispose() { this.isDisposed = true; } } // Activatable Mixin class Activatable { isActive: boolean; activate() { this.isActive = true; } deactivate() { this.isActive = false; } } class SmartObject implements Disposable, Activatable { constructor() { setInterval(() => console.log(this.isActive + " : " + this.isDisposed), 500); } interact() { this.activate(); } // Disposable isDisposed: boolean = false; dispose: () => void; // Activatable isActive: boolean = false; activate: () => void; deactivate: () => void; } applyMixins(SmartObject, [Disposable, Activatable]); let smartObj = new SmartObject(); setTimeout(() => smartObj.interact(), 1000); //////////////////////////////////////// // In your runtime library somewhere //////////////////////////////////////// function applyMixins(derivedCtor: any, baseCtors: any[]) { baseCtors.forEach(baseCtor => { Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => { derivedCtor.prototype[name] = baseCtor.prototype[name]; }); }); }
3. 三斜线指令
/// <reference path="..." /> 在文件头部,表明对其他文件的依赖