Typescript types are bonkers insane, so we could go as far as validate the templates. For example, showing error on '{DD}-{xx}' saying, that xx is not valid here.
Sample code with (lots of) comments on TS playground
Shortened code without comments:
typeFoo='a'|'b'|'c';typeReplaceWithFoo<Textendsstring>=Textends `${infer P}[string]${infer Rest}`
? `${P}[${Foo}]${ReplaceWithFoo<Rest>}`
: T;typeInferTemplateFromActual_Strict<Sextendsstring>=Sextends""
? ""
: Sextends `${infer P}[${Foo}]${infer Rest}`
? InferTemplateFromActual_Strict<Rest>extends infer R
? Rextendsstring
? `${P}[string]${R}`
: never
: never
: Sextends `${string}[${string}]${string}`
? never
: S;declarefunctionfn<Sextendsstring,Textendsstring=InferTemplateFromActual_Strict<S>>(str: SextendsReplaceWithFoo<T> ? S : never): T;// Valid calls:consttemplate1=fn("path/to/[a]/file");consttemplate2=fn("prefix-[b]-middle-[c]");consttemplate3=fn("no_placeholders");consttemplate4=fn("[a]-[b]");consttemplate5=fn("");// Invalid calls (should now correctly produce type errors):constinvalid1=fn("path/to/[string]/file");constinvalid2=fn("path/to/[d]/file");constinvalid3=fn("prefix-[a]-[d]");
Typescript types are bonkers insane, so we could go as far as validate the templates. For example, showing error on
'{DD}-{xx}'saying, thatxxis not valid here.Sample code with (lots of) comments on TS playground
Shortened code without comments: