#How to get inner join/intersection between 2 types?
1 messages · Page 1 of 1 (latest)
Preview:```ts
type GetIntersection<T extends Record<string,unknown>, Y extends Record<string,unknown>> = {
[Key in keyof T & keyof Y as [T[Key], Y[Key]] extends [Y[Key], T[Key]] ? Key : never]: T[Key];
}
type Test1 = GetIntersection<{a:string},{a:string, b:string}> // {a:string}
...```
Preview:```ts
type GetIntersection<T extends Record<string,unknown>, Y extends Record<string,unknown>> = T&Y
type Test1 = GetIntersection<{a:string},{a:string, b:string}> // {a:string}
type Test2 = GetIntersection<{a:string},{a:number, b:string}> // {}
type Test3 = GetIntersection<{a:string, b:string},{a:string, b:string}> // {a:string, b:string}
...```
Generating types by re-using an existing type.
each key is either remapped to itself (nothing changes) or never (gets removed)
keyof T & keyof Y common keys
[T[Key], Y[Key]] extends [Y[Key], T[Key]] ? Key : never if both values are the same type, the new key will be Key (nothing changes), otherwise its never (entire property gets removed)
the [A, B] extends [B, A] syntax is just a shorter way of doing A extends B ? B extends A ? true : false : false