Skip to content

Array#includes argument type is too narrow #36352

Closed
@aquark

Description

@aquark

TypeScript Version: my project uses 3.5.3 but I can see the issue is still present in the master branch.

Search Terms: Array includes

Code

const b: string = 'b'
['a' as const].includes(b)

Expected behavior:
It should compile. Specifically, the type definition for Array#includes should allow for any searchElement type:

interface Array<T> {
    /**
     * Determines whether an array includes a certain element, returning true or false as appropriate.
     * @param searchElement The element to search for.
     * @param fromIndex The position in this array at which to begin searching for searchElement.
     */
    includes(searchElement: unknown, fromIndex?: number): boolean;
}

It is type-safe to ask whether an array contains any value for the same reason it is type-safe to compare any two types with ===. The example above is a toy example but this pattern shows up all the time in real-world use, e.g. to check if a string is a member of a union of strings.

Actual behavior:
Argument of type 'string' is not assignable to parameter of type '"a"'

Related Issues: None found

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