Skip to content

Array.indexOf - searchElement is too Restrictive? #37434

Closed
@halfnibble

Description

@halfnibble

TypeScript Version: 3.8.3

Search Terms:
indexOf, too restrictive, searchElement

Expected behavior:
I expect Array.indexOf() to allow a searchElement with a type that includes and extends beyond the array. E.g. If the haystack is [2, 3], then I expect to the needle could be of type 1 | 2 | 3 and that a value of -1 would be returned if the needle is 1. But I do not expect a compiler error.

Actual behavior:
Compiler error.
Argument of type 'CoolNumbers' is not assignable to parameter of type '2 | 3'.
Type '1' is not assignable to type '2 | 3'. (2345)

Related Issues:
#29290
#35257

Code

type CoolNumbers = 1 | 2 | 3;

const B: CoolNumbers = 2;
const C: CoolNumbers = 3;

const A: CoolNumbers = Math.floor(Math.random() * 3 + 1) as CoolNumbers;

if ([B, C].indexOf(A) === -1) {  // <--- Error here.
    console.log('My favorite 2 numbers.');
} else {
    console.log("it's 1");
}
Output
"use strict";
const B = 2;
const C = 3;
const A = Math.floor(Math.random() * 3 + 1);
if ([B, C].indexOf(A) === -1) {
    console.log('My favorite 2 numbers.');
}
else {
    console.log("it's 1");
}
Compiler Options
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "declaration": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "moduleResolution": 2,
    "target": "ES2017",
    "jsx": "React",
    "module": "ESNext"
  }
}

Playground Link: Provided

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions