Home > Enterprise >  How to sequentially compare the types in two tuples?
How to sequentially compare the types in two tuples?

Time:11-22

I'd like to sequentially compare the types in two tuples and return a tuple containing 0's and 1's to represent matching and non matching types.

  1. The two tuples do not have to be of equal length
  2. The length of the outputted tuple will always match the length of T1
  3. The types are compared for an exact match

Code

type Equals<X, Y> = [X] extends [Y] ? [Y] extends [X] ? true : false : false;

type TupleElementComparison<T1 extends readonly unknown[], T2 extends readonly unknown[]> =
    {[K in keyof T1]: Equals<T1[K], T2[K]> extends true ?  1 : 0}

Example usage

Playground

type example1 = TupleElementComparison<[string, number], [string, number]>
// [1, 1]

type example2 = TupleElementComparison<[string, number], [string, number, Function]>
// [1, 1]

type example4 = TupleElementComparison<[string, number, boolean, number, Function, string], [number, boolean, string, string, Function, number]>
// [0, 0, 0, 0, 1, 0]

type example3 = TupleElementComparison<[string, number, boolean, number, Function, string], [string, number, boolean, number]>
// [1, 1, 1, 1, 0, 0]

Question

TupleElementComparison actually outputs the expected result - when you mouseover the resultant type in the playground - but i'm getting the following error when accessing T2 with K that i'm unable to fix

Type 'K' cannot be used to index type 'T2'.

Is there a way to fix this error?

CodePudding user response:

Yes, there is a way. You need to assure TS that K represents keyof T2.

type TupleElementComparison<T1 extends readonly unknown[], T2 extends readonly unknown[]> =
    {[K in keyof T1]:  Equals<T1[K], T2[K & keyof T2]> extends true ?  1 : 0}
  • Related