Maximus Maximus - 14 days ago 6
TypeScript Question

returning a function that doesn't match type alias doesn't produce an error - why?

I have the following type alias:

type MyDecorator = (target: Function) => Function | void;


And I then use it like this:

function z(): MyDecorator {
return function () {

}
}


And it's compiled without an error. Why? I expected to get an error since the function being returned doesn't take any parameters, although one parameter is specified in the type alias.

Answer

The reason that it won't throw an error is because the returned function does indeed satisfy MyDecorator.

This is because I can do this:

z()(() => { console.log("here"); });

The fact that the returned function doesn't have a parameter in its signature doesn't mean that it can not receive the param, you can also do this:

function z(): MyDecorator {
    return function () {
        let target = arguments[0] as Function;
    }
}

You will get an error if you have other params:

function z(): MyDecorator {
    return function (a: string) {

    }
}

Errors with:

Type '(a: string) => void' is not assignable to type 'MyDecorator'.
Types of parameters 'a' and 'target' are incompatible.
Type 'Function' is not assignable to type 'string'.