1

How to make recursive template literal type?

type MyType = 'A' | 'B' | 'C'
type MyTypesWithDot = `??` 
// (o) 'A.B' 'A.C' 'B.C' 'A.B.C' 'A.A.B'
// (o) 'A.A.A.A.B.B.A.C.{TOO MANY MyType}.A.B' ...
// (x) 'A.D' 'A..D' 'A.BB'

function myFunc(myArg: MyType) {
  // some code
}

I tryed infer keyword, generic, some other way.. but I can't :(

milkyway
  • 11
  • 2
  • Please see [here](https://tsplay.dev/WKpaow) and [here](https://stackoverflow.com/questions/68252446/is-it-possible-to-generate-string-literal-combinations-with-template-literal-in#answer-68256789). – captain-yossarian from Ukraine Feb 15 '23 at 09:09

1 Answers1

0
type MyTypesWithDot<T extends string> = T extends MyType
  ? T
  : T extends `${infer A}.${infer B}`
  ? `${MyTypesWithDot<A>}.${MyTypesWithDot<B>}`
  : never

function myFunc<T extends string>(myArg: MyTypesWithDot<T>) {
  // some code
}

the point is apply a recursive check by

T extends `${infer A}.${infer B}` ? `${MyTypesWithDot<A>}.${MyTypesWithDot<B>}`: never

and use T extends MyType to avoid infinite loop

Jerryh001
  • 766
  • 2
  • 11