You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为带参数与模板字面量的函数编写TypeScript类型定义?

给带前置参数的标签模板函数编写TypeScript类型定义

我完全懂你的困扰——给这类带前置参数的标签模板函数写TypeScript类型,官方文档确实没把这块讲得太明白。不过咱们可以利用TypeScript的TemplateStringsArray和类型约束来完美解决这个问题,下面一步步来拆解:

基础版:适配任意模板字面量

首先,先明确这种函数的调用结构:你先传两个普通参数,然后紧接着用标签模板的方式传递模板字面量。在TypeScript里,标签模板函数的模板部分会被拆解成两部分传递给函数:

  1. 一个TemplateStringsArray类型的字符串数组(对应模板里的固定字符串片段)
  2. 若干个插值参数(对应模板里${}包裹的内容)

结合你已经掌握的前两个参数类型,我们可以写出基础的函数类型:

// 假设你的前两个参数分别是 number 和 string,可根据实际情况替换
type CallFunc = (
  paramOne: number,
  paramTwo: string,
  // 模板的固定字符串片段,用TypeScript内置的TemplateStringsArray类型
  templateStrings: TemplateStringsArray,
  // 插值参数,这里用unknown[]表示任意类型的插值,如果有特定要求可以修改
  ...interpolatedValues: unknown[]
) => void; // 如果函数有返回值,把void换成对应的类型

// 声明第三方函数的类型
declare function callFunc: CallFunc;

// 现在这样调用就会通过类型检查了
const something = "user123";
const here = 456;
callFunc(100, "example")`stringLiteral: ${something}, somethingElse: ${here}`;

进阶版:约束插值参数的类型

如果第三方函数对模板里的插值有特定类型要求(比如第一个插值必须是字符串,第二个必须是数字),我们可以直接在函数签名里指定插值参数的类型:

type CallFuncWithConstrainedValues = (
  paramOne: number,
  paramTwo: string,
  templateStrings: TemplateStringsArray,
  // 第一个插值必须是string
  firstValue: string,
  // 第二个插值必须是number
  secondValue: number
) => void;

declare function callFunc: CallFuncWithConstrainedValues;

// 合法调用:插值类型匹配
callFunc(100, "example")`stringLiteral: ${"user123"}, somethingElse: ${456}`;

// 非法调用:第二个插值类型不对,会触发TypeScript报错
// callFunc(100, "example")`stringLiteral: ${"user123"}, somethingElse: ${"oops"}`;

高阶版:约束模板字面量的结构

如果需要更严格的约束,比如要求模板必须是stringLiteral: ${}, somethingElse: ${}这种固定格式,我们可以用泛型来约束templateStrings的数组类型:

// 定义模板必须匹配的字符串片段结构
type RequiredTemplateSegments = ["stringLiteral: ", ", somethingElse: ", ""];

type CallFuncWithStrictTemplate = <T extends RequiredTemplateSegments>(
  paramOne: number,
  paramTwo: string,
  templateStrings: T,
  firstValue: string,
  secondValue: number
) => void;

declare function callFunc: CallFuncWithStrictTemplate;

// 合法调用:模板结构完全匹配
callFunc(100, "example")`stringLiteral: ${something}, somethingElse: ${here}`;

// 非法调用:模板结构不符合要求,会触发报错
// callFunc(100, "example")`wrongKey: ${something}, somethingElse: ${here}`;

关键知识点总结

  • TemplateStringsArray是TypeScript内置的专用类型,专门用于标签模板函数的字符串片段参数,它继承自readonly string[],还包含raw属性(用于获取原始未转义的字符串)。
  • 当你使用callFunc(a,b)template`这种语法时,TypeScript会自动把模板拆分成字符串数组和插值参数,传递给函数的后续参数位置。
  • 可以根据第三方函数的实际行为,灵活调整插值参数的类型或模板结构的约束。

内容的提问来源于stack exchange,提问作者boydenhartog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:46:54