Consider the various types showcased for demonstration:
type TranslateToEnglish<A extends string> =
A extends "1" ? "one" :
A extends "2" ? "two" :
A extends "3" ? "three" :
"etc";
type ConvertNumberToString<A extends string> =
A extends `${infer C}${infer Tail}` ?
`${TranslateToEnglish<C>}-${ConvertNumberToString<Tail>}` : "";
For instance, using
ConvertNumberToString<"12">
will yield "one-two-"
.
Now, the goal is to increase its flexibility and allow a "translator" like TranslateToEnglish
to be passed as an argument:
type ConvertWithTranslator<A extends string, Translator> =
A extends `${infer C}${infer Tail}` ?
`${Translator<C>}-${ConvertNumberToString<Tail>}` : "";
This approach fails with the error:
Type 'Translator' is not generic. ts(2315)
Attempting to revise it as below results in another error:
type ConvertWithTypeParam<A extends string, Translator<_>> =
The error message shows: ',' expected. ts(1005)
at the <_>
.
Q: Is there a method to pass a parametric (generic) type as an argument to another type within TypeScript, Flow, or other JavaScript superset? Similar to higher-order functions but for types.