1

I'm trying to create a proxy for Angular components. Starting from this solution: https://github.com/Microsoft/TypeScript/issues/4890#issuecomment-141879451

I ended up with this:

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;
}

Usage:

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

That works. The problem is that it fails if I uncomment the constructor: heroService is undefined.

I think it has something to do with Angular's DI because the following works fine on TS Playground (constructor uncommented):

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();
Manuel
  • 10,869
  • 14
  • 55
  • 86
  • I think class `C` is missing the decorator metadata from the `@Component()`. Don't you get an error trying to add this to a `NgModule`? – Reactgular Apr 25 '19 at 00:56
  • I think you're on to something. How would you decorate it? With `@Component({})` I get `TypeError: Cannot read property 'kind' of undefined`. With `@Injectable()` I get `Can't resolve all parameters for C: (?)` – Manuel Apr 25 '19 at 02:02

0 Answers0