Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define an interface for a class instance using class constructor

I am building a application and part of the code allows developer to specify which component they want to render a certain part. I want users to know they need to implement an interface but I am not sure how to write typing correctly.

export interface ICustomComponent {
    templateObject: any;
}

export class MyComponent implements ICustomComponent {
}

export class MyLib {
    constructor(
        private yourComponent: ICustomComponent
    ) {}
}

new MyLib(MyComponent); <== Fails

I am writing code with Angular, and I cannot run new operator but let Angular to resolve and construct that component.

Here an example that illustrates my problem.

How to deal with this problem?

like image 706
tom10271 Avatar asked Feb 11 '26 21:02

tom10271


1 Answers

Since MyLib expects a class constructor, not class instance, you need to define an interface for a class constructor and specify that it returns the instance with the ICustomComponent interface:

interface ICustomComponent {
  templateObject: any;
}

interface ICustomComponentConstructor {
  new (...deps: any[]): ICustomComponent;
}

And then you can use it like this:

export class MyComponent implements ICustomComponent {
  templateObject: any;
}

export class MyLib {
  constructor(private yourComponent: ICustomComponentConstructor) {
  }
}

new MyLib(MyComponent);

You can read about interface for class constructors and instances here.

like image 178
Max Koretskyi Avatar answered Feb 15 '26 11:02

Max Koretskyi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!