【问题标题】:How to describe function with parameters and template literal?如何用参数和模板文字描述函数?
【发布时间】:2019-12-17 06:58:40
【问题描述】:

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

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

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

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

【问题讨论】:

标签: javascript typescript typescript-typings typescript-generics


【解决方案1】:

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,其他一切都取决于你的库的具体情况

【讨论】:

    猜你喜欢
    • 2011-08-08
    • 1970-01-01
    • 2019-06-16
    • 2013-03-25
    • 2018-06-03
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 2021-11-02
    相关资源
    最近更新 更多