Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Last active Oct 21, 2022
Embed
What would you like to do?
type _Tuple<
T,
N extends number,
R extends readonly T[] = []
> = R["length"] extends N ? R : _Tuple<T, N, readonly [T, ...R]>;
type Tuple<T, N extends number> = _Tuple<T, N> & {
readonly length: N;
[I: number]: T;
[Symbol.iterator]: () => IterableIterator<T>;
};
function zip<
A extends readonly any[],
Length extends A["length"],
B extends Tuple<any, Length>
>(a: A, b: B): Tuple<readonly [A[number], B[number]], Length> {
if (a.length !== b.length) {
throw new Error(`zip cannot operate on different length arrays; ${a.length} !== ${b.length}`);
}
return a.map((v, index) => [v, b[index]]) as Tuple<
readonly [A[number], B[number]],
Length
>;
}
const a = [1, 2, 3] as const;
const b1 = [1, 2, 6, 2, 4] as const;
const b2 = [1, 2, 6] as const;
// @ts-expect-error Source has 5 element(s) but target allows only 3.
const c1 = zip(a, b1);
const c2 = zip(a, b2);
console.log(c2);
// ^?
@sebinsua
Copy link
Author

sebinsua commented Oct 21, 2022

Unfortunately, regarding not matching on number, it doesn't seem possible to use extends in this way as by definition all numeric literals inherit from number. I guess we'd need TypeScript to add a NumberLiteral type that is the superset of all numeric literals in between individual numeric literals and number. (Maybe this type could just be an infinite number interval.)

And, regarding the possibility of using a runtime assertion of equal lengths (or some other property) to assign an opaque/branded/flavoured type to two or more values, this isn't currently possible as TypeScript doesn't support multiple/aggregate function assertions or propagation of type assertions outside of their scope.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment