Inversify child class with super method passing the argument to parent is not working

57 views Asked by At

When I try to pass the argument to parent class via super class in inversify there is argument error :

"message": "The number of constructor arguments in the derived 
class Child must be >= than the number of constructor arguments of its base class.",
"stack": "Error: The number of constructor arguments in the derived 
class Child must be >= than the number of constructor arguments of its base class.\n

Here is my child and parent class which looks correct:

Parent.ts

import { injectable } from 'inversify';

interface IParentInterface {
  someMethod(): void;
}

@injectable()
export class Parent implements IParentInterface {
  private readonly _topic: string;
  constructor(topic: string) {
    this._topic = topic;
    console.log('Parent constructor with topid', this._topic);
  }

  someMethod(): void {
    console.log('Parent method');
  }
}


child.ts

import { injectable } from 'inversify';
import { Parent } from './Parent';

@injectable()
export class Child extends Parent {
  constructor() {
    super('my_topic'); // Call the parent class constructor
    console.log('Child constructor');
    this.someMethod();
  }
}

Types file

types.ts

export const TYPES = {


  Parent: Symbol.for('parent'),
  Child: Symbol.for('Child')
};

main.ts

  const newContainers = new AsyncContainerModule(async (bind: interfaces.Bind) => {
      bind<Parent>(TYPES.Parent).to(Parent).inSingletonScope();
      bind<Child>(TYPES.Child).to(Child).inSingletonScope();
    });

    const app = new AppServer(
      [newContainers],
      serviceGlobalCustomMiddlewares
    );

    const childInstance = app.getContainer().get<Child>(TYPES.Child);

When I remove the super arguments it works

1

There are 1 answers

0
Mr X On BEST ANSWER

Got the answer:

We need to leverage the DI and inject the constant

@injectable()
export class Parent implements IParentInterface {
  private readonly _topic: string;
  constructor(@inject(TYPES.Topic) protected readonly topic: string) {
    this._topic = topic;
    console.log('Parent constructor with topid', this._topic);
  }

  someMethod(): void {
    console.log('Parent method');
  }
}

and In container we need to set this

 bind(TYPES.Topic).toConstantValue();