Home > Enterprise >  How to parse template string literal type to get the components
How to parse template string literal type to get the components

Time:11-11

Maybe without using as: How can I

type F = 'a' | 'b' | 'c'

type R = '11' | '22' | '33'

type P = `${F}${R}`


const p: P = `a11`

// is there a better way to parse this string?
function getFR(p: P): [F, R] {
  return [p[0] as F, p.slice(1) as R]
}

console.log(getFR(p))

CodePudding user response:

For a typescript-specific solution, if you are willing to to use strings as types, not values, you can use infer in template literals (see "we can infer from substitution positions" part), like in:

type F = 'a' | 'b' | 'c'

type R = '11' | '22' | '33'

type P = `${F}${R}`

type ExtractFR<T extends P> = T extends `${infer f extends F}${infer r extends R}` ? [f, r] : never;

type fr = ExtractFR<'a11'> // ['a', '11']

playground

CodePudding user response:

This is how I would do it.

www.typescriptlang.org

type F = 'a' | 'b' | 'c'

type R = '11' | '22' | '33'

type P = `${F}${R}`

const p: P = `a11`

const extract = <T extends P>(p: T): [F,R] => {
   const data: any = [p[0], p.slice(1)];
   return data;
}


console.log(extract("a11"))

as you see above you dont have to specify any casting as the method return :[F,R] will cast the data automatically. You still have to create a variable of type any though

  • Related