Home > database >  default value of Function as constructor parameter
default value of Function as constructor parameter

Time:03-03

following the solutions of this problem: Create a new object from type parameter in generic class

I have this simple code:

class TestBase {
    hi() {
        alert('Hi from base');
    }
}

class TestSub extends TestBase {
    hi() {
        alert('Hi from sub');
    }
}

class TestTwo<T extends TestBase = TestBase> {
    constructor(private testType: new () => T) { // Set TestBase constructor as default value for testType ?
    }

    getNew() : T {
        return new this.testType();
    }
}

//var test = new TestTwo<TestBase>(TestBase);
var test = new TestTwo<TestSub>(TestSub);

var example = test.getNew();
example.hi();

// With a default value for testType, I will be able to write something like:
var test2 = new TestTwo();
test2.getNew().hi(); // Should print "Hi from base"

How is it possible to set a default value for testType constructor within testTwo constructor ?

Thanks for help

CodePudding user response:

You can't, because this is valid code:

class TestSub3 extends TestBase { prop3: number = 42; }
class TestSub4 extends TestBase { prop4: string = "answer"; }
// ...
const test3 = new TestTwo<TestSub3>(); // Note no argument = uses default
const test4 = new TestTwo<TestSub4>(); // Note no argument = also uses default

There's no default constructor you can provide that satisfies that code, because for test3 it would have to provide something creating a TestSub3 and for test4 it would have to provide something creating a TestSub4.

You might consider having a function that returns a class instead, probably an overloaded one so that it can return something creating TestBase classes if you provide no argument for it, but some type that extends TestBase when you do.

  • Related