Skip to content
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

TS implicitly typing array in conditional #40864

Closed
JGJP opened this issue Oct 1, 2020 · 1 comment
Closed

TS implicitly typing array in conditional #40864

JGJP opened this issue Oct 1, 2020 · 1 comment

Comments

@JGJP
Copy link

JGJP commented Oct 1, 2020

let someVar = null as null | number
// other logic here
if ([0, 1].includes(someVar)) {
	// do something
}

Expected behavior:

No problem is returned.

Actual behavior:

TS returns the following problem on someVar in the if statement:

Argument of type 'number | null' is not assignable to parameter of type 'number'.
  Type 'null' is not assignable to type 'number'. ts(2345)

Meanwhile, changing the conditional from [0, 1].includes(someVar) to ([0, 1] as (null|number)[]).includes(someVar) fixes the problem. Why does Typescript implicitly type the array in this instance? The array isn't assigned so won't be used anywhere else, I don't see the utility in requiring this extra syntax here.

It would be nice to be able to use Array.includes() as shorthand for a bunch of || operators such as in someVar === 0 || someVar === 1.

Playground Link:

https://www.typescriptlang.org/play?#code/DYUwLgBAzg9gtiAagQwE4QLwQHYFdjATJQ76EA+pcARiKgFAD0jEMYAFnRMDAOYCWAYwidUIevwBmEABQBtAAwAaCAEYAugDp+2QcFwATEFBmwEKVAEpLEAN70AkMwgGY0eOHY7e9AL5A

Related Issues:

Could not find related issues

@JGJP JGJP changed the title TS not properly recognising Array.includes() in conditionals TS implicitly typing array in conditional Oct 1, 2020
@JGJP
Copy link
Author

JGJP commented Oct 1, 2020

Seems to be a duplicate of #36275

@JGJP JGJP closed this as completed Oct 1, 2020
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

No branches or pull requests

1 participant