Search code examples
typescriptstring-interpolation

How to accept number with dot separator using string interpolation?


How to create a function that accept number with dot separator.

For example

func('100.000.002.333') // pass
func('10') // pass
func('20') // pass
func('100') // pass
func('20') // pass
func('0100.000') // error
func('1000') // error
func('000.000') // error leading 0
func('100.000.') // error trailing dot
func('100.00.000') // error
func('.100.00.000') // error leading dot

Solution

  • playground
    Works exactly as the code you've provided in the comment, but is much shorter and simplier

    type Split<S extends string, P extends string = ""> =
        | S extends `${infer A}${P}${infer B}` ?
        B extends '' ? [A, B] : [A, ...Split<B, P>]
        : S extends '' ? [] : [S]
    
    type x = Split<'.1234.56.', '.'>
    //   ^?
    //   type x = ["", "1234", "56", ""]
    
    type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
    // 1-3 digit number not starting with 0
    type FirstNumber = `${Exclude<Digit, '0'>}${'' | Digit}${'' | Digit}`;
    // 3-digit number
    type MiddleNumber = `${Digit}${Digit}${Digit}`;
    type Ok<S extends string> =
        | S extends '0' ? '0' // corner case: allow literal '0'
        : Split<S, '.'> extends [FirstNumber, ...MiddleNumber[]] ? S : false
    
    declare function func<S extends string>(arg: Ok<S>): S;