【问题标题】:Infer Types from Tagged Template Literal Function argment从标记的模板文字函数参数推断类型
【发布时间】:2021-10-01 17:04:25
【问题描述】:

我想在标记的模板文字函数中从通用参数中获取类型。

但打字稿无法从参数“模板”中读取。它只是读取类型为 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[];
}
*/

有没有办法将template理解为['hello ', '']

【问题讨论】:

  • 你能澄清value在你的问题中是什么吗?
  • 有趣的问题。我从来没有以这种方式使用模板文字

标签: typescript


【解决方案1】:

这里的主要问题是TemplateStringsArray 没有参数化。见this issue

但是你仍然可以推断出模板文字函数的第一个参数以外的所有参数:

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'}`;

Playground

如果你想推断整个字符串,你应该为每个单词使用${},或者使用带有推断字符串参数的常规函数​​。 如果您想了解有关函数参数类型推断的更多信息,可以查看我的article

附:如果您对此功能感兴趣,请点赞:thumb-up: above issue

【讨论】:

  • 那太糟糕了。我需要什么取决于第一个参数,所以我想要做的功能是不可能的。我试过实现...args 类型取决于第一个模板字符串类型。
猜你喜欢
  • 2019-09-12
  • 1970-01-01
  • 2016-07-16
  • 1970-01-01
  • 2012-04-18
  • 1970-01-01
  • 2023-03-31
  • 2015-02-06
  • 1970-01-01
相关资源
最近更新 更多