TypeScript Cannot Invoke an Expression whose Type Lacks a Call Signature

I have a love|hate relationship with TypeScript. I love it when it works & hate it when it doesn't do what I think it should. I was trying to clean up some code and wrote the following:

function filterContent(content:ContentTypeA[]|ContentTypeB[]) {
    return content.filter((value) => {
        //a bunch of code to check if item should be removed or not
        return true;
    });
}

This resulted in a warning "Cannot invoke an expression whose type lacks a call signature". "Type 'blah' has no compatible call signatures". Parameter 'value' implicitly has an 'any' type. In English, this means I used union types incorrectly.

I was trying to say my content parameter could be an array of values with ContentTypeA and ContentTypeB. My syntax was wrong though. The above example says that content can be an array whose values are all either ContentTypeA or ContentTypeB. You can't mix the two types together in the same array.

To do that use one of the following syntaxes below.

function filterContent(content:Array<ContentTypeA|ContentTypeB>) {
    return content.filter((value) => {
        //a bunch of code to check if item should be removed or not
        return true;
    });
}
function filterContent(content:(ContentTypeA|ContentTypeB)[]) {
    return content.filter((value) => {
        //a bunch of code to check if item should be removed or not
        return true;
    });
}

I hope this prevents a headache for someone else who misunderstands how to properly do union arrays.

Matt Ferderer

Full Stack Software Developer focused on JavaScript and C#. Love to share & help others make amazing things. Have a project you need help on? Let's talk!

comment

Comments