34007-medium-compare-array-length

Back

// your answers

type CompareArrayLength<T extends any[], U extends any[]> = T extends [infer TH, ...infer TRest] 
? ( U extends [infer UH, ...infer URest] ? CompareArrayLength<TRest, URest> : 1) 
: ( U extends [infer UH, ...infer URest] ? -1 : 0)

Solution by hhk9292 #35106

type LessThan<A extends any[], B extends any[]> = A extends [infer AF, ...infer ARest extends any[]]
  ? B extends [infer BF, ...infer BRest extends any[]]
    ? LessThan<ARest, BRest>
    : false
  : A['length'] extends B['length']
    ? false
    : true

type CompareArrayLength<T extends any[], U extends any[]> = T['length'] extends U['length'] ? 0 : LessThan<T, U> extends true ? -1 : 1

Solution by XkSuperCool #34891

// your answers
type CompareArrayLength<T extends any[], U extends any[]> = T extends []
  ? U extends [] 
    ? 0
    : -1
  : T extends [infer FirstT,...infer RestT]
    ? U extends []
      ? 1
      : U extends [infer FirstR,...infer RestR]
        ? CompareArrayLength<RestT,RestR> : never
    : never

Solution by waakemeup #34833

type CompareArrayLength<T extends number[], U extends number[]> =
  T[`length`] extends U[`length`] ? 0 :
  T[`length`] extends 0 ? -1 :
  U[`length`] extends 0 ? 1 :
  T extends [number, ...infer RT extends number[]] ? U extends [number, ...infer RU extends number[]] ? CompareArrayLength<RT, RU> :
  never : never;

Solution by E-uler #34714

// T = [1, 2], U = [3, 4, 5]
// keyof T = 0 | 1, keyof U = 0 | 1 | 2
type CompareArrayLength<T extends any[], U extends any[]> = T['length'] extends U['length'] ? 0 : keyof T extends keyof U ? -1 : 1

Solution by ouzexi #34175

type CompareArrayLength<T extends unknown[], U extends unknown[]> = T['length'] extends U['length']
  ? 0
  : `${U['length']}` extends keyof T ? 1 : -1;

Solution by alexandroppolus #34089

type CompareArrayLength<T extends any[], U extends any[]> = T['length'] extends U['length']
  ? 0
  : Fill<T, any> extends [...Fill<U, any>, ...any]
    ? 1
    : -1

type Fill<T extends any[], K> = T extends [any, ...infer Rest]
  ? [K, ...Fill<Rest, K>]
  : []

Solution by Sun79 #34069

type CompareArrayLength<T extends unknown[], U extends unknown[]>
  = keyof T extends keyof U ? keyof U extends keyof T ? 0 : -1 : 1

Playground

Solution by teamchong #34061

type CompareArrayLength<
  T extends any[],
  U extends any[]
> = T["length"] extends U["length"]
  ? 0
  : T extends [infer _, ...infer TR]
  ? U extends [infer _, ...infer UR]
    ? CompareArrayLength<TR, UR>
    : 1
  : -1

Solution by ScriptBloom #34060