Skip to content

TS implicitly typing array in conditional #40864

Closed
@JGJP

Description

@JGJP
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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions