Search code examples
interfacetypescriptmixins

Typescript- Using class as interface, why do I have to implement private members/methods?


I'm using the Mixin pattern as illustrated below. Why does Typescript require you to provide stand-in properties for private properties of the mixin class in the target class (A)? It perfectly makes sense for the public properties, but for private properties it unnecessarily crufts up the target class with details of the internal implementation of the mixin class by requiring them to be stubbed-out in the target class. Seems like the Typescript transpiler should be able to not require this.

class Mixin {
    private foo:string;
}

class A implements Mixin {
   // stand-in properties, typescript requires even
   // private properties to be stubbed-out 
   foo:string;
}

Solution

  • Private members contribute to the structure of a type in TypeScript, so if you don't implement them you are not compatible with the type. This actually makes it impossible to match a type structurally in TypeScript if it has a private member, because you are either:

    a. Failing to provide the type

    or

    b. Providing a separate implementation of the private member

    So you can only extend a type with a private member, not implement it.

    With this in mind, you are better off not using private members with mixins. Provide the ghost-members in the implementation class and keep your fingers crossed that if mixins gain some traction the ghosting will become unnecessary (see TypeScript mixins part one).