Skip to content

Using an array union type A[] | B[] gets evaluated to A | B when accessing an element of the array #52084

@jose-adalo

Description

@jose-adalo

Bug Report

Using an array union type A[] | B[] gets evaluated to A | B when accessing an element of the array

🔎 Search Terms

array union,
union of arrays,
accessing an element,
union of custom typed arrays,
accessing an array element

🕗 Version & Regression Information

V3.3.3 to
V4.9.4
(All typecript playground versions)

⏯ Playground Link

Playground link with relevant code

💻 Code

interface A {
      children:A[]
      a: number
}

interface B {
      children:B[]
      b: number
}

const func = (obj: A[] | B[]):void => {
      obj[0].children = [obj[1]]
      obj[0].children.push(obj[1])
}

🙁 Actual behavior

This gives a compilation error

Type '(A | B)[]' is not assignable to type 'A[] | B[]'.
  Type '(A | B)[]' is not assignable to type 'A[]'.
    Type 'A | B' is not assignable to type 'A'.
      Property 'a' is missing in type 'B' but required in type 'A'.(2322)

🙂 Expected behavior

No errors,
if obj is A[], then obj[1] is of type A and can be assigned to obj[0].children = [ obj[1] ],
else the same applied but with B

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions