DEV Community

Acid Coder
Acid Coder

Posted on • Edited on

Typescript Greater Equal Or Lesser

type level numeric comparator

export type CreateArrayWithLengthX<
    LENGTH extends number,
    ACC extends unknown[] = []
> = ACC['length'] extends LENGTH
    ? ACC
    : CreateArrayWithLengthX<LENGTH, [...ACC, 1]>

export type CompareAToB<
    A extends number[],
    B extends number[]
> = A['length'] extends B['length']
    ? 'equal'
    : A extends [infer C, ...infer D extends number[]]
    ? B extends [infer M, ...infer N extends number[]]
        ? CompareAToB<D, N>
        : 'greater'
    : B['length'] extends 0
    ? 'equal'
    : 'lesser'

type E = CompareAToB<CreateArrayWithLengthX<99>,CreateArrayWithLengthX<100>> // lesser
//   ^?
type F = CompareAToB<CreateArrayWithLengthX<100>,CreateArrayWithLengthX<100>> // equal 
//   ^?
type G = CompareAToB<CreateArrayWithLengthX<101>,CreateArrayWithLengthX<100>> // greater
//   ^?
Enter fullscreen mode Exit fullscreen mode

playground

max valid number is 1000

Top comments (0)