我正在为我的项目正在使用的第三方模块创建类型。
其中一个函数是这样调用的:
callFunc(paramOne, paramTwo)`
stringLiteral: ${something},
somethingElse: ${here}
`;
我试图弄清楚如何在 typescript 中描述这样的功能,但 typescript 文档在这种特定情况下并没有真正帮助。前两个参数我知道如何描述,但如何为模板/字符串文字添加类型?
最佳答案
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${0}b`
在您的例子中,函数 callFunc(paramOne, paramTwo)
返回一个标记模板,因此定义应该类似于:
declare function callFunc(paramOne: string, paramTwo: number) : (s: TemplateStringsArray, ...a:any[]) => string;
callFunc("", 1)`a${0}`
对参数类型做了一些假设,但除了 TemplateStringsArray
其他一切都取决于你的库的细节
关于javascript - 如何用参数和模板文字来描述函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57431669/