Skip to content

Too narrow typing for Array.prototype.includes #48247

Closed
@kulak-at

Description

@kulak-at

Bug Report

The type for Array.prototype.includes seems to be too narrow making it hard to use in many use cases. Currently Array<T> would use T as a parameter for searchElement which makes it impractical when used to check against optional types:

const arr = [
    "a",
    "b",
    "c",
];

const fn = (val: string | number): val is string => {
    return arr.includes(val);
}

The code above should work properly but instead val is too wide typing to be passed to it.

The issue is even more prevalent when used with as const keyword:

const arr = [
    "a",
    "b",
    "c"
] as const;

const isInConstArray = (val: string): boolean => {
    return arr.includes(val); // Error, Argument of type 'string' is not assignable to parameter of type '"a" | "b" | "c"'.
}

🔎 Search Terms

🕗 Version & Regression Information

Seems to be old bug, I could reproduce it in 3.9.7 which seems to be the first to understand .includes syntax on the Playground.

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about Array / includes

⏯ Playground Link

Playground link with relevant code

💻 Code

const arr = [
    "a",
    "b",
    "c"
];

const isInConstArray = (val: string | number): boolean => {
    return arr.includes(val);
}

🙁 Actual behavior

Error when passing val as parameter to arr.includes.

🙂 Expected behavior

arr.includes should accept wider type and behave like type guard instead.

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