Last active
March 20, 2023 11:21
-
-
Save Emiltayeb/93257e468ae875b9636f96f992fea5d4 to your computer and use it in GitHub Desktop.
Type Advance types - array intersection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Construct a type that checks if 2 array are interscting | |
type ToUnion<T extends unknown[]> = T[number]; | |
type IntersectionArrays<T extends any[], U extends any[]> = T["length"] extends 0 ? true : | |
{ [K in ToUnion<T>]: K extends ToUnion<U> ? false : true }[ToUnion<T>] extends true ? true : never | |
// Will resolve true since no intersection found | |
type A = IntersectionArrays<[1], [2]> | |
// Will resolve never since both array have the item "1" inside | |
type B = IntersectionArrays<[1], [1]> | |
// You can also twick the type to aslo return the actual araay passed as a type | |
type IntersectionArrays<T extends any[], U extends any[]> = | |
{ [K in ToUnion<T>]: K extends ToUnion<U> ? false : true }[ToUnion<T>] extends true ? T extends (infer U)[] ? U[] : never : never | |
// will resolve to (1)[] | |
type A = IntersectionArrays<[1], [2]> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment