我怎样才能解决这种矛盾的导入



我有两个类开关。由于我已经在不同的文件中分离了这两个类,现在我有一个自相矛盾的导入:

  • 导入开关呼叫开关(本(

  • 交换机导入以解析其接口。

灯.ts

import Switch from './switch.ts';
export default class Lamp {
    state: 'on' | 'off' = 'off';
    constructor () {
        Switch.on(this);
    }
}

开关

import Lamp from './lamp.ts';
export default class Switch {
    static on (lamp: Lamp) {
        lamp.state = 'on';
    }
    static off (lamp: Lamp) {
        lamp.state = 'off';
    }
}

你可以创建一个接口,我们称之为SwitchableLamp可以实施。

这样Switch依赖于抽象而不是具体的Lamp类。

它看起来像这样:

interface Switchable {
  state: 'on' | 'off';
}
class Lamp implements Switchable {
  state: 'on' | 'off' = 'off';
  constructor() {
    Switch.on(this);
  }
}
class Switch {
  static on(switchable: Switchable) {
    switchable.state = 'on';
  }
  static off(switchable: Switchable) {
    switchable.state = 'off';
  }
}

这是带有代码的操场链接。

最新更新