0

I'm struggling to understand where the problem with this implementation is. I have created a simple test class that implements a very simple interface with a constructor and the Typescript compiler is saying there is a problem.

BaseEntity.ts:

export interface IBaseEntity {
  id: string
  new(_id?: string, _data?: any)
}

Test.ts:

class Test implements IBaseEntity {
  id: string
  constructor(_id?: string, _data?: any) {
    this.id = 'MOCK_ID'
  }
}

error:

Class 'Test' incorrectly implements interface 'IBaseEntity'.
  Type 'Test' provides no match for the signature 'new (_id?: string | undefined, _data?: any): any'.

I'm hoping someone can quickly point out where the issue is because it seems to me this is correct. Thanks in advance all.

1 Answer 1

6

This is a miss understanding of what implements does. implements ensures that the instance type of the class fulfills the contract specified by the interface. The constructor of the class is not part of the instance type, it is part of the class type (the static part of the class).

You need to segregate the static part of the interface form the instance part:

export interface IBaseEntity {
  id: string

}

export interface IBaseEntityClass {
    new(_id?: string, _data?: any): IBaseEntity
}


class Test implements IBaseEntity {
  id: string
  constructor(_id?: string, _data?: any) {
    this.id = 'MOCK_ID'
  }
}
let baseEntityClass: IBaseEntityClass = Test; // The class test fulfills the contract of IBaseEntityClass

new baseEntityClass("", {}) // constructing through IBaseEntityClass interface

Playground Link

There is currently no way to specify that the class type needs to implement a specific interface, but you would get errors on the assignment let baseEntityClass: IBaseEntityClass = Test if Test did not have the right constructor.

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.