交集类型将多种类型组合成一种。这允许您将现有类型添加到一起以获得具有所需功能的单一类型。

    1. function extend<T, U>(first: T, second: U): T & U {
    2. let result = <T & U>{};
    3. for (let id in first) {
    4. (<any>result)[id] = (<any>first)[id];
    5. }
    6. for (let id in second) {
    7. if (!result.hasOwnProperty(id)) {
    8. (<any>result)[id] = (<any>second)[id];
    9. }
    10. }
    11. return result;
    12. }
    13. class Person {
    14. constructor(public name: string) { }
    15. }
    16. interface Loggable {
    17. log(): void;
    18. }
    19. class ConsoleLogger implements Loggable {
    20. log() {
    21. // ...
    22. }
    23. }
    24. var jim = extend(new Person("Jim"), new ConsoleLogger());
    25. var n = jim.name;
    26. jim.log();


    混入,的原理是将两个对象的所有可枚举属性合并,然后返回一个新的对象。

    1. // Disposable Mixin
    2. class Disposable {
    3. isDisposed: boolean;
    4. dispose() {
    5. this.isDisposed = true;
    6. }
    7. }
    8. // Activatable Mixin
    9. class Activatable {
    10. isActive: boolean;
    11. activate() {
    12. this.isActive = true;
    13. }
    14. deactivate() {
    15. this.isActive = false;
    16. }
    17. }
    18. class SmartObject implements Disposable, Activatable {
    19. constructor() {
    20. setInterval(() => console.log(this.isActive + " : " + this.isDisposed), 500);
    21. }
    22. interact() {
    23. this.activate();
    24. }
    25. // Disposable
    26. isDisposed: boolean = false;
    27. dispose: () => void;
    28. // Activatable
    29. isActive: boolean = false;
    30. activate: () => void;
    31. deactivate: () => void;
    32. }
    33. applyMixins(SmartObject, [Disposable, Activatable]);
    34. let smartObj = new SmartObject();
    35. setTimeout(() => smartObj.interact(), 1000);
    36. ////////////////////////////////////////
    37. // In your runtime library somewhere
    38. ////////////////////////////////////////
    39. function applyMixins(derivedCtor: any, baseCtors: any[]) {
    40. baseCtors.forEach(baseCtor => {
    41. Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
    42. derivedCtor.prototype[name] = baseCtor.prototype[name];
    43. });
    44. });
    45. }