educative.io

Can you call functionWithOverload with three parameters?

In this example that was given in this lesson, the last function overload has three parameters. So why is it that I can’t call it with three parameters? If I say:

console.log(functionWithOverload(1, “test”, “test”));

The compilation will fail with the error “index.ts(9,45): error TS2554: Expected 1-2 arguments, but got 3.”
If I comment out the first two function overloads, then the call with three parameters works.

I understand that the last function overload is an aggregation of all the overloads, so why does it have three parameters when the first two function overloads have 1 and 2 parameters respectively?


Course: Learn TypeScript: The Complete Course for Beginners - Learn Interactively
Lesson: Overload Functions to Enrich your Definition - Learn TypeScript: The Complete Course for Beginners

Hi @Yunfei_Xie !!
In TypeScript, when you define multiple function overloads, the implementation signature is typically more permissive than the overload signatures. In this case, the last function overload has three parameters, but it allows for optional and default parameter values.

When you call the functionWithOverload function with three arguments (1, "test", "test"), TypeScript tries to match the provided arguments with the available overload signatures. It starts from the top and checks if any overload signature is a valid match. In this case, the first two overload signatures don’t match because they expect fewer parameters.

Since the third overload signature allows for three parameters (with the third parameter being optional), TypeScript tries to match the call with this signature. However, it encounters a problem because the second parameter, "test", is not assignable to the type string | undefined (since string is not compatible with string | undefined).

To make the call with three parameters work, you would need to modify the implementation of the last function overload to handle the third parameter properly, such as checking if param3 is undefined or not, and returning the appropriate value.

Here’s an example modification to make the call with three parameters work:

function functionWithOverload(param1: number): boolean;
function functionWithOverload(param1: number, param2: string): string;
function functionWithOverload(param1: number, param2: string = "default", param3?: string): boolean | string {
    if (param3 !== undefined) {
        return true;
    } else if (param2 === "test") {
        return "test";
    }
    return false;
}

console.log(functionWithOverload(1, "test", "test")); // Outputs: "test"

Now, the modified implementation handles the case where the third parameter is provided, and it returns the expected result.
I hope it helps. Happy Learning :blush:

2 Likes