Skip to content

Type narrowing for if (!Array.isArray(a)) { fails to eliminate a readonly array #57566

@brad4d

Description

@brad4d

🔎 Search Terms

"Array.isArray", readonly, narrow, "!Array.isArray"

🕗 Version & Regression Information

  • This is the behavior in every version I tried from the latest back to 4.9.5, and I reviewed the FAQ for entries about Array.isArray, narrowing, and readonly arrays.

⏯ Playground Link

https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABMAFAQwFyLCAtgIwFMAnRAH0WMLQBMEAbAT2zyOIG0BdASkQG8AUIkQxgiFAEIAgsWJpGAOhgBnGXMbpuvQcOEQEyuPUIL6cAObpEAakRpuAbiGIAvgLcDQkWAkSXMLAQk5IFsXNrOouLSsvJKqrEa9hG6iPpghsamFla29k7Cbm5AA

💻 Code

function f(a: number | readonly number[]) {
  if (!Array.isArray(a)) {
    console.log(a + a); // error here
  }
}

function g(a: number | number[]) {
  if (!Array.isArray(a)) {
    console.log(a + a); // no error here
  }
}

🙁 Actual behavior

TypeScript reports "Operator '+' cannot be applied to types 'number | readonly number[]' and 'number | readonly number[]'."

for the a + a expression inside

function f(a: number | readonly number[]) {
  if (!Array.isArray(a)) {
    console.log(a + a); // error here
  }
}

🙂 Expected behavior

Expect that narrowing variable a of type number | readonly number[] using if (!Array.isArray(a)) { should narrow the type of a to number.
That is what happens when a is of type number | number[].

Additional information about the issue

No response

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