简体   繁体   中英

How to describe function with parameters and template literal?

I'm creating typings for a third party module that my project is using.

One of the functions is called as such:

callFunc(paramOne, paramTwo)`
  stringLiteral: ${something},
  somethingElse: ${here}
`;

I'm trying to figure out how to describe such a function in typescript but the typescript documentation didn't really help in this specific case. The first two parameters I know how to describe but how do I add a typing for the template / string literal?

Tagged templates are functions where the first argument is of type TemplateStringsArray and then the rest of the arguments are just the values of expressions in the template. So for example we can define t :

function t(s: TemplateStringsArray, ...a:any[]) {
  console.log(t); // will output ["a", "b"]  for the example below
  console.log(a); // will output [0] for the example below
  return ""
}

t`a${0}b`

In your case the function callFunc(paramOne, paramTwo) returns a tagged template, so the definition should look something like:

declare function callFunc(paramOne: string, paramTwo: number) : (s: TemplateStringsArray, ...a:any[]) => string;


callFunc("", 1)`a${0}`

Made a few assumptions about parameter types, but except for TemplateStringsArray everything else is dependent on the specifics of your library

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM