1

我正在尝试为 Angular 组件创建代理。从这个解决方案开始: https ://github.com/Microsoft/TypeScript/issues/4890#issuecomment-141879451

我最终得到了这个:

interface Type<T> {
  new (...args): T;
}

interface Base {}

interface Identifiable {}

export function IdentifiableSubclass<T extends Base>(SuperClass: Type<T>) {
  class C extends (<Type<Base>>SuperClass) {
    // constructor(...args) {
    //   super(...args);
    //   return new Proxy(this, {
    //     get(target, name) {
    //       return target[name];
    //     }
    //   });
    // }
  }
  return <Type<Identifiable & T>>C;
}

用法:

@Component({...})
class HeroesComponent {
  constructor(public heroService: HeroService) {}
}
const HeroesComponentLogged = IdentifiableSubclass(HeroesComponent);
export { HeroesComponentLogged as HeroesComponent };

这样可行。问题是如果我取消对构造函数的注释它会失败:heroService is undefined

我认为这与 Angular 的 DI 有关,因为以下在 TS Playground 上运行良好(构造函数未注释):

class HeroService {
    public sayGoodbye() {
        console.log("Goodbye");
    }
}
class HeroComponent {
     constructor(public heroService: HeroService) {
    }
}

const IdentifiedHeroComponent = IdentifiableSubclass(HeroComponent);
let identified = new IdentifiedHeroComponent(new HeroService());
identified.heroService.sayGoodbye();
4

0 回答 0