Description
lib Update Request
Change the first argument type of Array.prototype.includes
from the generic type based on array type to any
or unknown
and make it a typeguard.
Configuration Check
My compilation target is ES2020
and my lib is ES2020
.
Sample Code
Supose you are building an API with Node.js and you receive an user input parsed as JSON. That input could be anything, then you type it as unknown
for type safety. But you need to ensure that input belongs to a set of specific values. Let's say ['foo', 'bar']
.
Then, you write the following code
// previous logic
const allowedValues = ['foo', 'bar'] as const;
if (!allowedValues.includes(userInput)) {
// some error handling
}
// additional logic
This will trigger an error on TypeScript since userInput
is typed unknown
. Two possible workarounds are
if (!(allowedValues as [unknown, unknown]).includes(userInput)) {
// some error handling
}
if (!allowedValues.includes(userInput as string)) {
// some error handling
}
Both of them are ugly and the second one also makes the wrong assumption that userInput is a string.
It would be ideal if Array.prototype.includes
was a typeguard (if an array of strings contains a value, then that value must be a string).