Does typescript provide any means to get a callable constructor properly typed in generic way?
The below code works but has a few issues. Seems you just can't modify the constructor return type through a declaring class or interface. I tried to play around with a mixin but couldn't get it to work.
interface Callable<T> {
(): T;
(value:T): this;
}
declare class O<T> {
constructor(value:T);
}
function O<T>(value:T) : Callable<T> {
let _value = value;
// can we get rid of this cast ?
const callable = <Callable<T>> function(value?:T){
if(value === undefined){
return _value;
}
_value = value;
return callable;
};
Object.setPrototypeOf(callable, O.prototype);
return callable;
}
// can we get rid of this cast and/or make it generic ?
const instance = new O(false) as Callable<boolean>;
const a = instance(); // false
instance(true);
const b = instance(); // true
const c = instance instanceof O; // true
Pretty sure there's other improvements to be made feel free to comment