Last active
July 3, 2020 14:16
-
-
Save karol-majewski/8db2d67b4220ce0e45078286168241e0 to your computer and use it in GitHub Desktop.
Type-safe zipping with TypeScript
This file contains hidden or 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
declare function zip<T extends readonly unknown[] | [unknown], U extends readonly unknown[] | [unknown]>( | |
left: T, | |
right: U & { length: T['length'] }): { | |
[K in keyof T & keyof U]: [T[K], U[K]] | |
} | |
zip([1, 2], ['one', 'two']); | |
zip([1, 2] as const, ['one', 'two'] as const); | |
zip([1, 2, 3], ['one', 'two']); // Compile-time error |
This file contains hidden or 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
declare function zip<T extends unknown[] | [unknown], U extends unknown[] | [unknown]>( | |
left: T, | |
right: T & { length: T['length'] }): { | |
[K in keyof T]: [T[K], T[K]] | |
} | |
zip([1, 2, 3], [4, 5]); // Compile-time error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment