5

I have an union of unknown types. I want to get a merge type of it. For example:

const a = {
    x: 10
}
const b = {
    y: 'qwer'
}

const array = [a, b]

type TArr = typeof array
// I use a function which receives an array as argument so I only have type of array from now on

type TUnion = keyof TArr[number] // { x: number } | { y: string }
type TMerge = ? // { x: number } & { y: string }

Where TMerge is practically the same as

type TMerge = {
  x: number
  y: string
}

I can't determine what types are in an array as originally array consists of different classes which used as modules. Without such union merging my final class doesn't know about all the methods and properties.

I assume it's impossible to get merged type right from array because &'s ambiguity between intersection and merge but if there's a trick I would love to hear it.

SpekalsG3
  • 155
  • 1
  • 8
  • I've seen several similar completely overshadowed [this question](https://stackoverflow.com/q/50374908/12222572) which has the answer – SpekalsG3 Sep 12 '21 at 01:27
  • 1
    There's a lot of caveats with turning an undifferentiated union into an intersection or a merge. You'd be better off with a tuple type (where the array elements are in a known order) than an array type. You can see the different possibilities [in this code](https://tsplay.dev/WzoVQw), which I mostly copied from the answers to the other questions. – jcalz Sep 12 '21 at 01:32

0 Answers0