Hone logo
Hone
Problems

Type-Level Comparison of Numbers

This challenge focuses on implementing type-level comparisons for numeric literal types in TypeScript. This is a fundamental technique for building more sophisticated type-level utilities and enabling compile-time checks based on numeric relationships. You will create a type that determines if one number is strictly less than another.

Problem Description

Your task is to create a TypeScript utility type called IsLessThan<T, U> that takes two numeric literal types, T and U, and returns true if T is strictly less than U, and false otherwise. This comparison should be performed entirely at the type level, meaning no runtime code is involved.

Key Requirements:

  1. Type-Level Operation: The comparison must be entirely within TypeScript's type system.
  2. Numeric Literal Types: The input types T and U will be constrained to be positive integer literal types (e.g., 1, 5, 100).
  3. Boolean Output: The type should resolve to true or false.

Expected Behavior:

  • IsLessThan<1, 2> should resolve to true.
  • IsLessThan<5, 5> should resolve to false.
  • IsLessThan<10, 3> should resolve to false.

Edge Cases to Consider:

  • Zero is not explicitly covered by the positive integer constraint for this challenge, but be mindful of how your logic would handle it if it were allowed.
  • The problem statement limits to positive integers. You do not need to handle negative numbers or non-integers.

Examples

Example 1:

type Result1 = IsLessThan<3, 7>;
// Expected: true

Explanation: 3 is indeed less than 7.

Example 2:

type Result2 = IsLessThan<10, 5>;
// Expected: false

Explanation: 10 is not less than 5.

Example 3:

type Result3 = IsLessThan<4, 4>;
// Expected: false

Explanation: 4 is not strictly less than 4.

Constraints

  • T and U will always be positive integer literal types (e.g., 1, 2, 3, ...).
  • The maximum value for T and U will not exceed 1000 to keep the recursion depth manageable for typical TypeScript configurations.
  • No runtime JavaScript code should be generated for the comparison logic itself. The solution should be purely type-level.

Notes

This problem often involves a recursive approach. Consider how you might break down the problem of comparing two numbers into smaller, comparable steps. Think about base cases for your recursion. You might find it helpful to define auxiliary types for manipulating numbers at the type level. Good luck!

Loading editor...
typescript