0

I have the following typescript function:

function normalize(value: number) {
    if (value < 0 || value > 30) {
        throw "The value should be between 0 and 30";
    }
}

Is there a way to write the function to display the exception compile time instead of run time?

Something like this:

function normalize(value: [0 - 30]) {
    f (value < 0 || value > 30) {
        throw "The value should be between 0 and 30";
    }
}
Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130
  • 1
    There are a number of typescript libraries that implement `refined types`? Did you have a chance to look at any of them? – sinanspd Feb 26 '21 at 23:21
  • It seems that could be a good solution. But I was looking for something native, in other words, looking if typescript supports something that can solve my problem without the need of external libraries. – Ricardo Rocha Feb 26 '21 at 23:26
  • Typescript can use unions on types to restrict the value range, but then you'd have to list all integers between 0 and 30. e.g. `type MyType = 0 | 1 | ... | 30` – ccarstens Feb 26 '21 at 23:30
  • @ccarstens It not the perfect solution, but I think I can work with that. – Ricardo Rocha Feb 26 '21 at 23:33
  • That's fair. You might be able to get some of that with type guards but I honestly don't know how much of that is actually compile time. – sinanspd Feb 26 '21 at 23:33

0 Answers0