AngryHacker
AngryHacker

Reputation: 61606

How to achieve C#/Java like constructor chaining in TypeScript?

Consider the following C# class:

class Foo
{   
    public Foo(int id, string name)
    {        
    }

    public Foo(int id) : this(id, "")
    {          
    }        
}

The same approach in TypeScript doesn't quite work:

class Foo {
    constructor(id: number, name: string) {
    }

    // fails here
    constructor(id: number) this(id, "") {
    }    
}

Is there a practical way to achieve constructor chaining?

The idea is to be able to call new Foo(1, "frank") and new Foo(1).

Upvotes: 0

Views: 185

Answers (1)

JB Nizet
JB Nizet

Reputation: 691715

JavaScript, and therefore TypeScript do not support constructor or method overloading, so you can't have more than one constructor implementation in your class.

One way to achieve the desired behaviour would be to use default parameters:

class Foo {
    constructor(id: number, name: string = '') {
    }
}

Relevant documentation (But I strongly suggest you read all of it)

Upvotes: 2

Related Questions