Closed
Description
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.