Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Last active July 3, 2020 14:16
Show Gist options
  • Save karol-majewski/8db2d67b4220ce0e45078286168241e0 to your computer and use it in GitHub Desktop.
Save karol-majewski/8db2d67b4220ce0e45078286168241e0 to your computer and use it in GitHub Desktop.
Type-safe zipping with TypeScript
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
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