Proposal: Add Overloads to Array.prototype.includes
and ReadonlyArray.prototype.includes
for Improved Type Safety and Usability
#61618
Labels
Declined
The issue was declined as something which matches the TypeScript vision
Suggestion
An idea for TypeScript
🔍 Search Terms
ReadonlyArray includes type-guard
✅ Viability Checklist
⭐ Suggestion
Add an overload to
Array.prototype.includes
andReadonlyArray.prototype.includes
that narrows the type of the searched value when the array is a literal tuple (e.g., declared withas const
) containing only primitive literal values such as strings, numbers, booleans,null
, orundefined
.This overload enables stricter type checking for
includes
calls and allows usingincludes
as a type guard only when it is safe and meaningful to do so, avoiding false assumptions when working with general arrays.Supporting Utility Types:
You can try it in the TypeScript Playground here
📃 Motivating Example
Currently, code like the following produces a type error, even though it is semantically correct:
To avoid this error, users often resort to unsafe casts or unnecessary widening of the array's type. On the other hand, relaxing the parameter type (e.g., using
unknown
) can lead to incorrect code such as:The proposed overload solves this by enabling proper narrowing only when it is safe (i.e., when the array is a literal tuple of literals), and producing compile-time errors when there is no possible match.
💻 Use Cases
1. What do you want to use this for?
To safely narrow the type of a variable when checking its inclusion in a fixed set of literal values using
.includes
, especially in configuration validation, value guards, and API parameter checks.2. What shortcomings exist with current approaches?
includes
does not currently act as a type guard even when used with literal tuples.unknown
) eliminates type safety and allows obvious mistakes.3. What workarounds are you using in the meantime?
key is 'a' | 'b' | 'c'
)Set.has()
instead of arraysas any
The text was updated successfully, but these errors were encountered: