Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

default value of Function as constructor parameter

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks for help

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading