Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Include method implementation in the interface in typescript

I have an interface which will be implemented by multiple classes:

interface I {
  readonly id: string;
  process(): void;
}

I would like to be able to pass id through a constructor such as:

class A implements I {...}
let a: A = {id: "my_id"} // or new A("my_id");

I don’t want to repeat the implementation of the default constructor in every implementation class, like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class A implements I {
  constructor(id: string){ this.id = id }
}

I tried putting the implementation of the constructor in the interface itself, but but a "cannot find id" error.

Is it possible to do in TS?

>Solution :

no it’s not possible see here.

you could do something like this however:

interface IMyInterface {
    readonly id: string;
    process(): void;
}

class ParentClass {
    id: string;
    constructor(id: string) {
        this.id = id;
    }
}

class SubClassOne extends ParentClass implements IMyInterface {
    process(): void {
        throw new Error('Method not implemented.');
    }
}
class SubClassTwo extends ParentClass implements IMyInterface {
    process(): void {
        throw new Error('Method not implemented.');
    }
}

const myclassOne = new SubClassOne('123');
const myclassTwo = new SubClassTwo('123');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading