Repository navigation
Some array methods should allow passing values of any typeΒ #42351
Description
Suggestion
π Search Terms
- Array.prototype.includes should allow passing values of any type
- Array.prototype.indexOf should allow passing values of any type
β Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
β Suggestion
Perhaps we could allow passing a generic type for array methods that search for the existence of something within an array as const so the developer can choose whether they want to allow this or not (and default to the current behavior).
The same would be useful for anything trying to find a value within an array (not just includes, but also indexOf)
π Motivating Example
Currently, I am experiencing this:
Playground link with relevant code
const a = ['one', 'two', 'three'] as const
const isFirstThreeNumbers = (type: string): type is typeof a[number] => a.includes(type)
// ^
// Argument of type 'string' is not assignable to parameter of type '"one" | "two" | "three"'.(2345)
isFirstThreeNumbers('four') // <-- false
isFirstThreeNumbers('three') // <-- trueWe're getting a ts(2345) error because the array can only contain certain elements.
This limitation that I cannot check whether an arbitrary value exists within the array + have a type guard that stays in sync with the array.
My workaround:
const isFirstThreeNumbers = (type: string): type is typeof a[number] => a.includes(type as typeof a[number])This is technically incorrect casting (because type could be anything), but I can't declare type as typeof a[number] because then consumers would only be allowed to pass values that are within the array values negating the usefulness of the function in the first place.
π» Use Cases
I think the use cases are very general. My specific use case is to determine whether a certain "exercise type" is within a given array:
const exerciseTypes = ['final', 'exercise', 'instruction'] as const
const isExerciseType = (type: string): type is typeof exerciseTypes[number] =>
// .includes *should* allow you to pass any type, but it does not :-(
exerciseTypes.includes(type as typeof exerciseTypes[number])
Activity
RyanCavanaugh commentedon Jan 14, 2021
See #26255 / #14520
Using type guard here is not sound due to its behavior in the false case; see #26255 (comment)
kentcdodds commentedon Jan 16, 2021
Gotcha! Thank you for the references Ryan Cavanaugh (@RyanCavanaugh)!