Mixins

除了传统的 OO 层次结构之外,另一种从可重用组件构建类的流行方法是通过组合更简单的部分类来构建它们。您可能熟悉 Scala 等语言的 mixin 或特征的概念,并且该模式在 JavaScript 社区中也颇为流行。

Mixin 是如何工作的?

该模式依赖于使用具有类继承的泛型来扩展基类。TypeScript 最好的 mixin 支持是通过类表达式模式完成的。您可以阅读有关此模式在 JavaScript 此处 中如何工作的更多信息。

开始之前,我们需要一个类,它会将 mixins 应用在:

class Sprite {
  name = "";
  x = 0;
  y = 0;

  constructor(name: string) {
    this.name = name;
  }
}

然后你需要一个类型和一个工厂函数,它返回一个扩展基类的类表达式。

// To get started, we need a type which we'll use to extend
// other classes from. The main responsibility is to declare
// that the type being passed in is a class.

type Constructor = new (...args: any[]) => {};

// This mixin adds a scale property, with getters and setters
// for changing it with an encapsulated private property:

function Scale<TBase extends Constructor>(Base: TBase) {
  return class Scaling extends Base {
    // Mixins may not declare private/protected properties
    // however, you can use ES2020 private fields
    _scale = 1;

    setScale(scale: number) {
      this._scale = scale;
    }

    get scale(): number {
      return this._scale;
    }
  };
}

完成这些设置后,您可以创建一个类,该类代表应用了 mixins 的基类:

class Sprite {
  name = "";
  x = 0;
  y = 0;

  constructor(name: string) {
    this.name = name;
  }
}
type Constructor = new (...args: any[]) => {};
function Scale<TBase extends Constructor>(Base: TBase) {
  return class Scaling extends Base {
    // Mixins may not declare private/protected properties
    // however, you can use ES2020 private fields
    _scale = 1;

    setScale(scale: number) {
      this._scale = scale;
    }

    get scale(): number {
      return this._scale;
    }
  };
}
// Compose a new class from the Sprite class,
// with the Mixin Scale applier:
const EightBitSprite = Scale(Sprite);

const flappySprite = new EightBitSprite("Bird");
flappySprite.setScale(0.8);
console.log(flappySprite.scale);

受约束的 Mixin

yi9W9pj+zY+Nmx3msa/s7a49JByifCWHQfefr3N7T99FmR9NsBQUOZ4a/qwktPLAKyZXVhjIBeLPAW0dFIYnXsafuHS/7ToAXDfK0oMQN9TbG0P4gHOaNFqhvFzlXbnFJWdrPuxc/uDXUpT8eCf8Hw==

X6ylhy/YqtQiavx3sof8hcqZQu+1uusiV3FcQSzhDdPoK8ek+L3tkg0p1f8+4uxzYMSsiiuUrchENs7X7P9czzPh0ft9F3HnKD09WAdUVGls1cdPVpK5pq9KSb0HcAic

// This was our previous constructor:
type Constructor = new (...args: any[]) => {};
// Now we use a generic version which can apply a constraint on
// the class which this mixin is applied to
type GConstructor<T = {}> = new (...args: any[]) => T;

TSn3M3ZVzeaLB5LQ+mEvXwtu56qjCPzI3aoialEi5+2C+Sp1HBE2AqRYQ76TnvVtExAVZ8Tv60ba8TpYyzoW3Q==

type GConstructor<T = {}> = new (...args: any[]) => T;
class Sprite {
  name = "";
  x = 0;
  y = 0;

  constructor(name: string) {
    this.name = name;
  }
}
type Positionable = GConstructor<{ setPos: (x: number, y: number) => void }>;
type Spritable = GConstructor<Sprite>;
type Loggable = GConstructor<{ print: () => void }>;

INpQGjJ+fRQSG2Om5UJ+Jk0hnxm3QCnpDcMOlgeuFnUfz5hL4CSmq/luay6N5DJu/03zj8ivZ7YKfujm06bYGbBPKXvG8oHVdnuMRR3W/lRpZiAaFn/1i4zvM+EXhp5b

type GConstructor<T = {}> = new (...args: any[]) => T;
class Sprite {
  name = "";
  x = 0;
  y = 0;

  constructor(name: string) {
    this.name = name;
  }
}
type Positionable = GConstructor<{ setPos: (x: number, y: number) => void }>;
type Spritable = GConstructor<Sprite>;
type Loggable = GConstructor<{ print: () => void }>;

function Jumpable<TBase extends Positionable>(Base: TBase) {
  return class Jumpable extends Base {
    jump() {
      // This mixin will only work if it is passed a base
      // class which has setPos defined because of the
      // Positionable constraint.
      this.setPos(0, 20);
    }
  };
}

替代模式

gtT0cbrOd+Cni1gUXGKKwuk9K8Ue/QwP8LhabYd/BSrsY4D7KAWXjz0JokrS0/w+SGwnqStb3NnPZN9iVB/7B2TBHhZPYQ7w68kuRmOWHNsQvynT0v4jHwXzhScC37MdmE+2RNNay19dHE85AflBzbp/WKXlZz1wD0/mwpWSCaV1Y6E/NBKRHp/3SpOqJyqGXOdoe2VNOsq19chDauI7SA==

// Each mixin is a traditional ES class
class Jumpable {
  jump() {}
}

class Duckable {
  duck() {}
}

// Including the base
class Sprite {
  x = 0;
  y = 0;
}

// Then you create an interface which merges
// the expected mixins with the same name as your base
interface Sprite extends Jumpable, Duckable {}
// Apply the mixins into the base class via
// the JS at runtime
applyMixins(Sprite, [Jumpable, Duckable]);

let player = new Sprite();
player.jump();
console.log(player.x, player.y);

// This can live anywhere in your codebase:
function applyMixins(derivedCtor: any, constructors: any[]) {
  constructors.forEach((baseCtor) => {
    Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
      Object.defineProperty(
        derivedCtor.prototype,
        name,
        Object.getOwnPropertyDescriptor(baseCtor.prototype, name) ||
          Object.create(null)
      );
    });
  });
}

jm1DUxbiz9DwMwCgsXOfgeSAB87T9Op3IffRKeJLcBNd5eKxe4D4y1uEZjIVaXpRXABbL71fcSTMwKWM03Jcplvnlvxjsj4oH/jRlvAxI9zWVUV5pjNVT8ihNHnifr3MlcRD7wmb//Gz/HrMJyqN5L00Ur24h4YLFiAUIFW7p97bqVZ1b8AlTP78Jb+P7+uB

约束条件

Z4oI+pGc6cWf4vWlneJRhwkL9MkxiaTxb8VbKSiVWyx21JgTvXy3bZrGYOF2hkCBCEwC9LWmNeGnGo0P10TzpEYE0dUuSSpE+IKRnwhlknaqlH7CRZVbwz21bhIea6lcUBWDujSgdDdNfvYolvO2eMi8Br8woLGUvz5SQk3taxEKOqAAaplPRKyw6LzIBJbH

装饰器和 Mixins #4881

ce6OY3vFlTKv6cggX4AQBzo/7Rr5dwFxbNWvULBA9dh7Oh+8XgdXYGnmcDCoE6/2ptYngjqH30O6IIwK/waDQA==

// A decorator function which replicates the mixin pattern:
const Pausable = (target: typeof Player) => {
  return class Pausable extends target {
    shouldFreeze = false;
  };
};

@Pausable
class Player {
  x = 0;
  y = 0;
}

// The Player class does not have the decorator's type merged:
const player = new Player();
player.shouldFreeze;

// The runtime aspect could be manually replicated via
// type composition or interface merging.
type FreezablePlayer = Player & { shouldFreeze: boolean };

const playerTwo = (new Player() as unknown) as FreezablePlayer;
playerTwo.shouldFreeze;

静态属性混合 #17829

3QUd2/nJnoM1tPp1yFQKniAq94UZu/2DIisLxdQpJnPh0Xyyee8zON9biam43v68XW44GzQTrQ3JXBpwNEkNg7D8mxcuoGxuL2/Kw3Dyeoo6REstdDJVhxmkOOaRFnJZyKdZd2x5UsxoL68j16CA86Int2i8eW0OnLBuG95uVZQX7hNDxE3dxL1bEIb74RF4o8XcY1pp3dV6RPGHal3lnQ==

51rklDLoVq9FGFkyOiChkHzTvLdV+VjaE41DVhj8pAQE/qxBBFRh3gcCt/FmFg5t8srDRuYhwRV7BCJqi2oFFHrqPnHLWoRQjia0UWlGop0=

function base<T>() {
  class Base {
    static prop: T;
  }
  return Base;
}

function derived<T>() {
  class Derived extends base<T>() {
    static anotherProp: T;
  }
  return Derived;
}

class Spec extends derived<string>() {}

Spec.prop; // string
Spec.anotherProp; // string