We have seen how can we add two numeric literals type
now can we apply similar tricks for subtraction?
yes we can, this is how we do it:
type CreateArrayWithLengthX< LENGTH extends number, ACC extends unknown[] = [], > = ACC['length'] extends LENGTH ? ACC : CreateArrayWithLengthX<LENGTH, [...ACC,1]> type Subtraction<LARGER extends number, SMALLER extends number, GAP extends number[] = []> = [...GAP,...CreateArrayWithLengthX<SMALLER>]['length'] extends [...CreateArrayWithLengthX<LARGER>]['length'] ? GAP['length'] : Subtraction<LARGER, SMALLER, [1,...GAP]> type result = Subtraction<849, 654> // 195
limitation: the number cannot exceed 999 because the max depth of TS recursion is only 1000, only work with positive integer
Top comments (0)