gvergnaud / hotscript

A library of composable functions for the type-level! Transform your TypeScript types in any way you want using functions you already know.
3.52k stars 58 forks source link

[Feature Request] Support for `Digit` and `Digits` #39

Open brandonmcconnell opened 1 year ago

brandonmcconnell commented 1 year ago

It would be helpful to be able to specify Digits and Digit types.

Definitions

import * as H from 'hotscript'

type Digits<T extends number> = H.Eval<H.Unions.Range<
  H.Eval<H.N.Power<10, H.Eval<H.N.Sub<T, 1>>>>,
  H.Eval<H.N.Sub<H.Eval<H.N.Power<10, T>>, 1>>
>> | (T extends 1 ? 0 : never);

type Digit = Digits<1>;

Usages

const some1DigitNumber: Digit = 5; // ✅
const some1DigitNumberString: `${Digit}` = "5"; // ✅
const some2DigitNumber: Digits<2> = 99; // ✅
const some2DigitNumberString: `${Digits<2>}` = "99"; // ✅

TypeScript Playground: https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAKjgQwM5wBJwGZQiOAcgAsIZUBjKYMGQg…


UPDATE: I've refined the example to include the recently supported Unions.Range.