Stav Alfi
Stav Alfi

Reputation: 13943

Merge 2 objects with same enum results in never

How can I merge both of the object types when there is an enum with 2 names:

enum e1 {
  bo = 'bo',
}

enum e2 {
  bo = 'bo',
}

type a1 = {
  a: e1
  b: number
}
type a2 = {
  a: e2
  c: string
}

type a12 = a1 & a2

// expected: { a: e1 (or e2), b: number, c: string }
// actual: never

https://www.typescriptlang.org/play?ssl=21&ssc=17&pln=1&pc=1#code/KYOwrgtgBMCMUG8BQUoCMD2UC8UDkmeANEgL5JKiQwBMiK6WuBGxZFALgJ4AOwUAQ3i5kqAQC4YsBmkngIaYACd23PoLoiGE2gwDGkgM4clASxABzdkjX8hmwfABkGigHo3MAB589HYAAmkgiCknBQABQYSrQAlETocpCKSgkGUMZmllDkHoJ+YAIANnLAAG7KQA

Upvotes: 0

Views: 47

Answers (1)

Rahul Sharma
Rahul Sharma

Reputation: 5995

Typescript assigned the type never to a12 as types of a1 and a2 aren't intersecting i.e. a can never be e1 and e2 at the same time. Type of a in a1 is Enum e1, while in a2 it's Enum e2. It would have the same result if we define types a1 and a2 like this:

type a1 = {
  a: 1
  b: number
}
type a2 = {
  a: 2
  c: string
}

type a12 = a1 & a2    //never

since types of a in a1 and a2 are non-intersecting. To have the expected type, you can do:

type a12 = Omit<a1, 'a'> & Omit<a2, 'a'> | { a: e1 | e2 };

Upvotes: 1

Related Questions