Typescript Greater Equal Or Lesser

tylim88

Acid Coder

Posted on August 19, 2022

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

💖 💪 🙅 🚩
tylim88
Acid Coder

Posted on August 19, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related