2

I can restrict the input validity to be a number but can I translate a string containing a number to an actual number ?

type ToNumber <S extends string> = S extends `${number}` 
    ? S                          // Change this ?
    : never

type test = ToNumber <'123'>    // is they're a way to get 123 instead of '123'

playground

zedryas
  • 718
  • 6
  • 19
  • 1
    [Here](https://tsplay.dev/mqEErm) you have working example. In current TS version it is possible to do only for numbers in range `0 .. 999`. It all depends on recursion limit. – captain-yossarian from Ukraine Jan 27 '22 at 13:17
  • 1
    thank you ;) Shall I delete the question since it's been previously answered ? – zedryas Jan 27 '22 at 13:20
  • 1
    No need to delete it. It will help other people to find appropriate answer. It is ok to have duplicates as long as they marked as such – captain-yossarian from Ukraine Jan 27 '22 at 13:21
  • @captain-yossarian do tout think it's possible to come up with a solution to handle negative numbers (bound as well) too ? I wrap my head around it but did came short ... – zedryas Jan 27 '22 at 14:14
  • AFAIK it is impossible to convert `"-5"` string representation to `5` numerical representation. You can't do such kind of math. It is possible to add and substract, but all these operations are done with help of tuple length. It is impossible to to represent tuple with negative length. However it is possible to validate literals. See [example](https://tsplay.dev/m355kw) – captain-yossarian from Ukraine Jan 27 '22 at 14:22

0 Answers0