Skip to content

Cannot type hint an arguments as two different Array shapes #11076

@whitneyit

Description

@whitneyit

TypeScript Version: Playground

function example(items: Array<Function> | Array<string>) {
    items.forEach(() => {
        // more code
    })  
}

A self-contained demonstration of the problem follows...

When trying to call items.forEach it squawks with the following error

Cannot invoke an expression whose type lacks a call signature.

It's weird because the intellisense suggests the forEach method but just typing items.forEach() is enough to get the compiler to complain.

Expected behavior:
I was expecting the above code to be valid so that I can perform the following code and narrow the type of item.

items.forEach(item => {
    if (typeof item === 'function') {
        // item is a Function
    } else if (typeof item === 'string') {
        // item is a String
    }
}) 

Actual behavior:
The compiler complains on any Array.prototype.* method

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions