0

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?

1 Answer 1

1

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');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.