typescript - Hur man parsar en template string literal-typ för att få komponenterna


Kanske utan att använda as: Hur kan jag

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))

Svar #1

För en TypeScript-specifik lösning, om du är villig att använda strängar som typer, inte värden, kan du använda infer i mall-litteraler (se delen "vi kan sluta oss från substitutionspositioner"), som i:

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']

lekplats

Svar #2

Så här skulle jag göra det.

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"))

Som du ser ovan behöver du inte specificera någon typomvandling eftersom metodens retur :[F,R] kommer att omvandla datan automatiskt. Du måste dock fortfarande skapa en variabel av typen any