TypeScript constructor

Nir Schwartz picture Nir Schwartz · Feb 22, 2016 · Viewed 8.9k times · Source

i tried to create a class with two constructors and find out that TypeScript are not allowing that, but it allow overloading of constructor, well I tried it to and get an error :

Build: Overload signature is not compatible with function implementation.

My code:

interface IShoppingListItem {
    name: string;
    amount: number;
}

export class ShoppingListItem implements IShoppingListItem{
    name: string;
    amount: number;

    constructor(item: IShoppingListItem);
    constructor(name: string, amount: number) {
        this.name = name;
        this.amount = amount;
    }

    copy() {
        //return new this.constructor(this);
    }
}

I have two question, first one, why can't I overloading the constructor, I guess I'm doing something wrong.

But my second question, and more interacting is, i know i constructor that get optional values. Can I, (not with the code inside the method!), create a condition on my constructor that can verify that one of the two given value have to exist, while in the signature boot are optional, like so:

constructor(item?: IShoppingListItem, name?: string, amount?: number) { 
//make a condition that item or name and amount must exist
    this.name = name;
    this.amount = amount;
}

Thanks.

Answer

John Weisz picture John Weisz · Feb 22, 2016

In Typescript, function overloading is nothing more than defining additional call signatures for a single function body. And since there is only one function body, all overload signatures must be compatible with that initial function declaration. Type- and value-checking of arguments are to be done manually.

In your case, it's a bit tricky, as interface definitions are lost upon compilation, therefore you'll have no clean approach to check if the passed argument is an implementation of the given interface. Luckily, it's an "object or string" check for your first parameter, and an "exists or not" for the second, so checking whether or not the interface is implemented is unnecessary:

export class ShoppingListItem implements IShoppingListItem {
    // 2 overload signatures from which you can choose on the invocation side
    constructor(item: IShoppingListItem);
    constructor(name: string, amount: number);

    // the function declaration itself, compatible with both of the above overloads
    // (in VS, IntelliSense will not offer this version for autocompletion)
    constructor(nameOrItem: string | IShoppingListItem, amount?: number) {
        if (typeof nameOrItem === "object") {
            // the first argument is an object, due to overload signature,
            // it is safe to assume it is of type IShoppingListItem

            // ...
        } else if (typeof nameOrItem === "string" && typeof amount === "number") {
            this.name = nameOrItem;
            this.amount = amount;
        }
    }
}

Here, both overloads are compatible with the initial signature. Parameter names do not matter, only their respective types and ordering (as well as optionality).

The TypeScript compiler is aware of typeof and instanceof checks, which results in your variable being treated as the correct type inside a conditional block as such. This is called a type guard.