I want get Types from Generic Argment in tagged template literal function.
but typescript cant read from argment 'template'. It just read type as TemplateStringsArray.
const tag = <T extends ReadonlyArray<string>>(template: T, ...args: string[]) => {
return {template, args};
};
const a = tag`hello ${'world'}`;
/**
const a: {
template: TemplateStringsArray;
args: string[];
}
*/
Is there any way to understand template
as ['hello ', '']
?
CodePudding user response:
The main problem here is that TemplateStringsArray
is not parameterized. See this issue.
But you can still infer all but first argument of template literal function:
const tag = <
Elem extends string,
Template extends ReadonlyArray<Elem>,
Arg extends string,
Args extends Arg[]
>(template: Template, ...args: [...Args]) => ({ template, args })
// const a: {
// template: TemplateStringsArray;
// args: ["world", "kiwi"];
// }
const a = tag`hello ${'world'} ${'kiwi'}`;
If you want to infer whole string, you either should use ${}
for each word or use regular function with infered string argument.
If you want to learn more about type inference on function arguments you can take a look at my article
P.S. If you are interested in this feature, please like :thumb-up: above issue