1

Как создать тип для числа, которое может меняться от 0 до 33 без конструкций if else

1 ответ 1

2

Как частичное решение можно использовать Tail-Recursion Elimination on Conditional Types. К сожалению работает только для целых чисел, с дробными не получиться.

type Enumerate<N extends number, Acc extends number[] = []> = Acc['length'] extends N
  ? Acc[number]
  : Enumerate<N, [...Acc, Acc['length']]>

type NumberRange<F extends number, T extends number> = Exclude<Enumerate<T>, Enumerate<F>>

type T = NumberRange<20, 30>

const a: T = 10; // type '10' is not assignable to type 'T'
const b: T = 20;
const c: T = 30; // type '30' is not assignable to type 'T'
const d: T = 40; // type '40' is not assignable to type 'T'
const f: T = 20.5; // type '20.5' is not assignable to type 'T'
1
  • Супер, мне и нужно с целыми числами). Спасибо 24 мар 2022 в 6:58

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.