Skip to content

Mixin classes with private/protected constructors are subclassableΒ #42264

Open
@rafasofizada

Description

@rafasofizada

Bug Report

πŸ”Ž Search Terms

mixin, private constructor

πŸ•— Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about Classes.
Versions tried:

  • 3.7.4
  • 4.1.3
  • Nightly

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

function PreventSubclassingMixin<TBase extends new(...args: any[]) => any>(Base: TBase) {
  return class NonSubclassable extends Base {
    private constructor(...args: any[]) {
      super();
    }
  }
}

class Base {
  constructor() {}
}

class NonSubclassableThroughExtension extends Base {
  private constructor() {
    super();
  }
}

const NonSubclassableThroughMixin = PreventSubclassingMixin(Base);

new NonSubclassableThroughExtension(); // Constructor of class 'NonSubclassableThroughExtension' is private and only accessible within the class declaration.(2673)
new NonSubclassableThroughMixin(); // Doesn't throw an error

πŸ™ Actual behavior

NonSubclassableThroughExtension correctly throw an error β€” I've extended a superclass Base, which has a publicly accessible constructor, and provided a private constructor in the derived class. I can't access the derived class' constructor anymore:

new NonSubclassableThroughExtension(); // Constructor of class 'NonSubclassableThroughExtension' is private and only accessible within the class declaration.(2673)

The PreventSubclassingMixin supposedly works the same β€” it creates a class expression that extends the Base class with a public constructor and defines a private constructor, and returns it. The returned derived mixin class is supposedly identical to the example above. However, if I apply the mixin to the Base: const NonSubclassableThroughMixin = PreventSubclassingMixin(Base), and try to initialize it, Typescript won't throw any error.

πŸ™‚ Expected behavior

new NonSubclassableThroughMixin() should throw a Constructor of class 'NonSubclassableThroughExtension' is private and only accessible within the class declaration.(2673).

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions