Im trying to define a pure class based mixin function, but I cannot get the type signature right for this one.
The intent is to provide a function that accepts any Class A as parameter and returns a new Class B that extends the original Class A.
export function mixin<A>(myclass: A) {
return class B extends A {
newMethod() {
//stuff
}
}
}
As I said, I cannot figure this out.
I need a way to express that A needs to be a class.
I also need to express the return type, which yields several errors, among:
error TS4060: Return type of exported function has or is using private name 'B'.
Additional information:
- This is inside a
utils.ts
module that is exported so that other modules can use it - This is all being worked in the context of a library I am writing
There's an open issue for this one: Allow class to extend from a generic type parameter
For now you can work around that with something like this:
(code in playground)
Which is based on code from here: extends dynamic Base class with generic throw an error
Edit
You can define an interface for the methods which will be added by the new class, something like:
(code in playground)
Then you can export the
B
interface and then you can use it anywhere.This code works well:
Output: