0

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

  • I'm not exactly sure what requirements you're looking for. Does calling `instance()` return a new instance of `O` or does it just return the currently stored value (in this case true or false). – jered Apr 02 '21 at 07:30
  • your code is invalid. it is hard to understand – captain-yossarian from Ukraine Apr 02 '21 at 07:49
  • I believe this is valid javascript but am struggeling with the typings for it. Although it's probably edge case? instanciating the class sets the initial value. then the instance is basically a get or set. No arg is get, arg is set. Run it and you'll see what it does :-) – Lode Michels Apr 03 '21 at 02:32

0 Answers0