如何在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
相关产品推荐
相关产品推荐

