DEV Community

Cover image for Advanced TypeScript Exercises - Question 10
Pragmatic Maciej
Pragmatic Maciej

Posted on

Advanced TypeScript Exercises - Question 10

Intersection type level operator & has changed in the last versions of TypeScript. The current behavior escalates 'never' type, so if any of fields will produce empty/never type, the whole composite will end as 'never'. Let's see some examples:

type X  = {
    a: 1
    b: number
}
type Y = {
    a: 2
    b: string
    c: boolean
}
// XY is never, as field 'a' evaluates as 1 & 2 which is never
type XY = X & Y 
Enter fullscreen mode Exit fullscreen mode

More about this TS behavior you can find here:

Exercise will be about having different intersection behavior. Our task is to write Merge type level function which will merge two product/object types. Our final Merge should be able to create a type from above X and Y in such a way that the latter type will overwrite types of fields of former type.

type XY = Merge<X,Y>
// XY should be {a: 2, b: string, c: boolean}
Enter fullscreen mode Exit fullscreen mode

Link to the playground with the task.

Good luck! If you have a solution then don't hesitate to link it in the comment. Answer will be published soon!

This series will continue. If you want to know about new exciting questions from advanced TypeScript please follow me on dev.to and twitter.

Top comments (6)

Collapse
 
hnicolas profile image
Nicolas Hervé

I curious to know if there is a simpler solution.
typescriptlang.org/play?#code/PTAE...

Collapse
 
sirmoustache profile image
SirMoustache

Here is mine: Playground

Collapse
 
macsikora profile image
Pragmatic Maciej

Really neat one 👍

Collapse
 
faiwer profile image
Stepan Zubashev

My solution: bit.ly/35ojBlc
code:

type Merge<A, B> = 
    & Omit<A, keyof B>
    & Omit<B, keyof A>
    & {
        [key in keyof A & keyof B]: (A[key] & B[key]) extends never
            ? A[key]
            : A[key] & B[key]
    };
Enter fullscreen mode Exit fullscreen mode

I hope I understand the task properly. Unfortunately my solution doesn't show anything except "XY" when you hover it. But it looks like it passes the test.

Collapse
 
faiwer profile image
Stepan Zubashev

in such a way that the latter type will overwrite types of fields of former type.

I didn't read it properly. But, BTW, my task is more interesting :)
My code really merges 2 objects. But it avoids "never" during merge. When there's never it takes the 2nd arguments value.

Collapse
 
nmonastyrskyi profile image
Nikita Monastyrskiy

It was a great series of exercises! Thank you, Maciej!

Here is my last solution