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
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); | |
// ^? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Unfortunately, regarding not matching on
number
, it doesn't seem possible to useextends
in this way as by definition all numeric literals inherit fromnumber
. I guess we'd need TypeScript to add aNumberLiteral
type that is the superset of all numeric literals in between individual numeric literals andnumber
. (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.