Skip to content

Array.includes() should accept any arg that extends the array's typeΒ #60073

Closed
@erikdstock

Description

@erikdstock

πŸ”Ž Search Terms

array.includes, types

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried - the type definition is 7 years old.

⏯ Playground Link

https://www.typescriptlang.org/play/?#code/MYewdgzgLgBAtgTwIICcUEMEC4bRQSzAHMBtAXRgF4YSAidWgGhloCNayBYAKB6gQAOAUxgBZTKyEA5AK4AbOVVxQCxGAB8YYeXJ6hIsASiEQhYKADV0cmUOr1aMdBDETpOveGjx8ECISIrGxF7YEcnF3EESVkFTwMtHSDbJW0FCNdo9zjebn1vEgQTZjAQZmh8BSkQCmoSHhhG+GQ0TAA6QmAbABMTAAojEzNLa1sASkYGpsRUDAQOsC6ZXog+uF9-YmShCanGmdb5zp7+tLltsZ4yIA

πŸ’» Code

No response

πŸ™ Actual behavior

I should not receive type errors because an argument of type string | null might be included in an array of type string[]. It is the job of the method to make the final determination.

πŸ™‚ Expected behavior

I get type errors because Array<string>.includes() will only accept a string value. I have to cast my argument to a string in order to perform the check.

Additional information about the issue

Relevant code.

Basic suggested change:

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: T, fromIndex?: number): boolean;
+    includes<U extends T>(searchElement: U, fromIndex?: number): boolean;}

interface ReadonlyArray<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: T, fromIndex?: number): boolean;
+    includes<U extends T>(searchElement: U, fromIndex?: number): boolean;}
// ...
}

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