typescripttypes

Can I slice literal type in TypeScript


In TypeScript, when I want to edit literal type, it is working.

type Old = "helloWorld"
//   ^? "helloWorld"
type New = `${Old}New`
//   ^? "helloWorldNew"

But how can I make this.

type Old = "helloWorld"
//   ^? "helloWorld"
type New = Slice<"helloWorld",5> // < Is it possible
//   ^? "World"

Solution

  • There is no Slice in ts, but maybe would a split match your needs ?

    type Split<S extends string, D extends string> =
        string extends S ? string[] :
        S extends '' ? [] :
        S extends `${infer T}${D}${infer U}` ? [T, ...Split<U, D>] : [S];
    

    Line 1 declares two params, we'll use single characters for brevity. S represents the string to split, and D is the deliminator. This line ensures they are both strings.

    Line 2 checks if string is a literal, by checking if a general string can be extended from the input string. If so, return a string array. We can't work with non-literal string.

    Line 3 checks if the string is empty, if so return an empty tuple

    type S2 = Split<"", "."> // string[]
    
    type S3 = Split<"1.2", "."> // ['1', '2']
    
    type S4 = Split<"1.2.3", "."> // ['1', '2', '3']
    

    Playground