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
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}
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)
I curious to know if there is a simpler solution.
typescriptlang.org/play?#code/PTAE...
Here is mine: Playground
Really neat one 👍
My solution: bit.ly/35ojBlc
code:
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.
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.
It was a great series of exercises! Thank you, Maciej!
Here is my last solution