Qwertiy
Qwertiy

Reputation: 21410

Overload with first optional parameter

How can I implement following logic?

function test(data: {x}, f: Function);
function test(f: Function);

function test(data: {x}, f: Function) {
    if (!f) {
        f = data;
        data = {x: 111};
    }

    return f(data);
}

test({x: 17}, t => 0);
test(t => 0);

It compiles in a right way, but shows 2 errors.

function test(data, f) {
    if (!f) {
        f = data;
        data = { x: 111 };
    }
    return f(data);
}
test({ x: 17 }, function (t) { return 0; });
test(function (t) { return 0; });

A place to test: http://www.typescriptlang.org/Playground

PS: Same question in Russian.

Upvotes: 0

Views: 74

Answers (1)

Qwertiy
Qwertiy

Reputation: 21410

I've found the solution:

function test(data: {x}, f: Function);
function test(f: Function);

//function test(data: {x} | Function, f?: Function) {
function test(data, f?) {
    if (!f) {
        f = data as Function;
        data = {x: 111};
    }

    return f(data);
}

The following calls are ok:

test({x: 17}, t => 0);
test(t => 0);

And the following aren't:

test({x: 17});
test(0);
test(t => 0, t => 0);

Any of these ways seems ok:

function test(data: {x} | Function, f?: Function) {
function test(data, f?) {

And explicit type cast is required:

f = data as Function;

Upvotes: 2

Related Questions