如何用参数和模板文字来描述函数?

How to describe function with parameters and template literal?

我正在为我的项目正在使用的第三方模块创建类型。

其中一个函数是这样调用的:

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

我正在尝试弄清楚如何在打字稿中描述这样的功能,但打字稿文档在这种特定情况下并没有真正帮助。前两个参数我知道如何描述,但如何为模板/字符串文字添加类型?

Tagged templates 是第一个参数类型为 TemplateStringsArray 的函数,其余参数只是模板中表达式的值。例如我们可以定义 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[=10=]b`

在你的例子中,函数 callFunc(paramOne, paramTwo) returns 是一个标记模板,所以定义应该类似于:

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


callFunc("", 1)`a[=11=]`

对参数类型做了一些假设,但除了 TemplateStringsArray 其他一切都取决于你的库的细节