-1

Say I have two types (just for example, I need something generic)

type TypeA = { propA: string};
type TypeB = { propB: number};

I would like to write a Generic type that would allow me to do something like this

type ABMerge = ArrayMerge<[TypeA,TypeB]>

// ABMerge would look like { propA: string, propB: number }

I've tried using generic and conditional types, but I can't figure out how to "iterate" over my Generic type array.

2 Answers2

2

The trick is to first 'overlay' all array elements onto one, using T[number]. That gives us a union of all types (like TypeA | TypeB).

Because you want to have an intersection type (TypeA & TypeB), we can then convert that union into an intersection using the nifty trick in this answer.

Full example:

type UnionToIntersection<U> =
    (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never

type ArrayMerge<T extends Array<any>> = UnionToIntersection<T[number]>;

// Test it:
type TypeA = { propA: number };
type TypeB = { propB: string };

const ab: ArrayMerge<[TypeA, TypeB]> = {
    propA: 42,
    propB: "x",
};

ab.propA; // number
ab.propB; // string

Check it out in the playground.

Martin Poelstra
  • 300
  • 1
  • 6
0

You can simply use the type intersection operator & in Typescript:

type A = { propA: number };
type B = { propB: string };

type AB = A & B;

const ab: AB = {
    propA: 42,
    propB: "hello, world",
};

See on the playground

Phillip
  • 6,033
  • 3
  • 24
  • 34
  • Sorry, I think my question didn't make it clear enough, but I don't always know the types A and B, thats why I need something more generic – Rama Rivera Aug 05 '19 at 08:29
  • @RamaRivera You don't need to know the types A and B in advance. You can use `A & B` just like you would write `a + b` without knowing about a and b. – GOTO 0 Aug 05 '19 at 09:25