如何动态地确保对象中的函数只使用它接受的参数调用?



考虑以下内容,

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
}
interface IGenerateText {
template: keyof typeof templates;
params: any;
}
const generateText = ({ template, params }: IGenerateText) => templates[template](params);

我如何用params: any重构这部分,以便typescript能够接收以下内容:

generateText({ template: 'templateA', params: { name: 'michael' } }); // no error
generateText({ template: 'templateA', params: { age: 5 } }); // error
generateText({ template: 'templateB', params: { age: 5 } }); // no error

这似乎很有效。我认为你也可以用一些聪明的方法去掉函数中的as any

const templateA = ({ name }: { name: string }) => `Hello, I am ${name}`;
const templateB = ({ age }: { age: number }) => `I am, ${age} years old`;
const templates = {
templateA,
templateB,
};
type TemplateName = keyof typeof templates;
interface IGenerateText<T extends TemplateName> {
template: T;
params: Parameters<typeof templates[T]>[0];
}
function generateText<T extends TemplateName>({ template, params }: IGenerateText<T>) {
return (templates[template] as any)(params);
}
generateText({ template: "templateA", params: { name: "michael" } }); // no error
generateText({ template: "templateA", params: { age: 5 } }); // error
generateText({ template: "templateB", params: { age: 5 } }); // no error

外部(即调用函数时),有一个映射类型(如typeof templates在您的情况下,templates是一个映射/字典)和一个推断的泛型类型参数选择映射类型的键,以表达一些函数参数之间的相关性,如在@AKX的回答中所做的。

但是在内部(即在函数体中),这种映射类型是不够的:TypeScript静态分析无法知道只使用了一个键类型(它仍然可以是键的并集),因此它退回到保留所有类型的并集。

告诉TS只存在一个键值的唯一方法是使用某种类型窄化。为了使TS缩小相关参数的类型,它们必须是判别并集的一部分。不幸的是,在您的情况下,这可能会导致一些重复的代码,目前无法避免以保持完全的安全性:

type Template = keyof typeof templates;
// Build a discrimated union from the templates map:
type DiscriminatedUnionTemplates = {
//^? { template: "templateA"; params: ITemplateA; } | { template: "templateB"; params: ITemplateB; }
// Use a mapped type:
[T in Template]: {
template: T;
params: Parameters<typeof templates[T]>[0]
}
}[Template] // Use indexed access to convert the mapped type into a union
const generateText = <T extends DiscriminatedUnionTemplates>({ template, params }: T) => {
// Narrow the type within the union,
// based on the `template` discriminant key
switch (template) {
case 'templateA': return templates[template](params); // Okay
case 'templateB': return templates[template](params); // Okay, repetitive but currently only way to keep full safety
}
};
generateText({ template: 'templateA', params: { name: 'michael' } }); // Okay
generateText({ template: 'templateA', params: { age: 5 } }); // Error: Object literal may only specify known properties, and 'age' does not exist in type 'ITemplateA'.
generateText({ template: 'templateB', params: { age: 5 } }); // Okay

操场上联系

在你的例子中,函数的内部作用很明显,我们可以接受类型断言,以避免重复的代码。

最新更新