1

I need to create this function overloads:

public groupBy(e: Expression<any>): T {
        e = this.convert(e, Role.GROUP_BY);
        this.metadata.addGroupBy(e);
        return this.self;
    }

    public groupBy(...o: Expression<any>[]): T {
        for (const e of o) {
            this.groupBy(e);
        }
        return this.self;
    }

I'm getting this compiler error:

Duplicate function implementation.

Any ideas?

1
  • 1
    Do you really need two public methods for this? Why not just have the varargs version delegate to a private single-arg version if needed? Commented Dec 1, 2017 at 20:07

1 Answer 1

3

Its a legitimate error. You can't have multiple method implementations, they have to be part of the same body. You can have a different method signature for your overloads but ultimately your implementation must support both. So for your snippet:

public from(arg: Expression<any>): T;
public from(...args: Expression<any>[]): T {
    // You must implement this method here so that it satisfies both
    // signatures...
    return this.self;
}

Although it looks like in this case you only need the one signature (since the other is basically a subset of the first), so just:

public from(...args: Expression<any>[]): T {
    // You must implement this method here so that it satisfies both
    // signatures...
    return this.self;
}

would suffice.

The important thing to note is that while you can describe the function signature via overloads, they all have to share the same implementation.

EDIT:

Per your comment and edited post, heres how it probably would have to look. Note that the same rules apply, you have to make sure that you properly distinguish which overload your using in the implementation:

public groupBy(e: Expression<any>): T;
public groupBy(...o: Expression<any>[]): T {
    if (o.length === 1) {
        // First overload, only a single argument.
        const e = o[0];
        e = this.convert(e, Role.GROUP_BY);
        this.metadata.addGroupBy(e);
    } else {
        // Second overload, either no or 2+ arguments...
        for (const e of o) {
            // Recursive call, but since we only give one argument, it
            // will use the code from the above code from the if block.
            this.groupBy(e);
        }
    }
    return this.self;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, I've forgotten that first from method implementation is important here. I've edited post code.
@Jordi check out the edit. Hopefully that satisfies your question, but feel free to ask for further clarification if I misunderstood what was asked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.