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

如何在TypeScript中实现模板函数的参数动态类型校验?

如何让TypeScript根据模板类型校验generateText的params参数类型?

直接把generateText改成泛型函数,利用TypeScript内置工具类型关联模板与对应参数的类型,彻底替换掉any,就能实现严格的类型校验。

重构后的完整代码

interface ITemplateA {
    name: string;
}
const templateA = ({ name }: ITemplateA) => `Hello, I am ${name}`

interface ITemplateB {
    age: number;
}
const templateB = ({ age }: ITemplateB) => `I am, ${age} years old`;

const templates = {
    templateA,
    templateB
}

// 重构为泛型函数实现类型绑定
const generateText = <T extends keyof typeof templates>({
    template,
    params
}: {
    template: T;
    params: Parameters<typeof templates[T]>[0];
}) => templates[template](params);

核心逻辑说明

  • 泛型T被约束为templates对象的合法键(keyof typeof templates),确保传入的template只能是已定义的模板名称。
  • Parameters<typeof templates[T]>[0]是关键:Parameters是TypeScript内置工具类型,用于提取函数的参数类型数组,[0]取第一个参数(因为每个模板函数都只接收一个对象参数),这样params的类型就和选中的模板函数的参数类型严格绑定。

测试验证

generateText({ template: 'templateA', params: { name: 'michael' } }); // ✅ 无错误
generateText({ template: 'templateA', params: { age: 5 } }); // ❌ 类型错误,templateA需要name参数
generateText({ template: 'templateB', params: { age: 5 } }); // ✅ 无错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 01:05:21