Home > Mobile >  Include method implementation in the interface in typescript
Include method implementation in the interface in typescript

Time:04-12

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:

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?

CodePudding user response:

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');
  • Related