Skip to content

Type for first argument in Array.prototype.includes #973

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
dfidalg0 opened this issue Jan 17, 2021 · 1 comment
Open

Type for first argument in Array.prototype.includes #973

dfidalg0 opened this issue Jan 17, 2021 · 1 comment

Comments

@dfidalg0
Copy link

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants