我有一个对象映射函数和一个接口(具有与对象相同的键)映射所述函数的参数类型.现在我试着编写一个函数,根据键的不同,可以调用任意一个函数.以下是问题的简化版本:
interface OneFProps {
a: string;
b: string;
}
const oneF = (props: OneFProps) => {
const { a, b } = props;
return `oneF ${a} ${b}`;
};
interface TwoFProps {
c: string;
d: string;
}
const twoF = (props: TwoFProps) => {
const { c, d } = props;
return `oneF ${c} ${d}`;
};
const funcMap = {
oneF: oneF,
twoF: twoF,
};
interface typeMap {
oneF: OneFProps;
twoF: TwoFProps;
}
type tags = keyof typeMap;
type BlendedProps<T extends tags> = {
key: T;
z?: string;
x?: string;
} & typeMap[T];
const blended = <T extends tags>(props: BlendedProps<T>) => {
const { key, z, x, ...rest } = props;
const func = funcMap[key];
return func(rest as any);
};
console.log(blended<'oneF'>({ key: 'oneF', a: 'AAA', b: 'bbb' }));
console.log(blended<'twoF'>({ key: 'twoF', c: 'ccc', d: 'DDD' }));
我不得不写rest as any
,因为我无法让 typewriter 工作.我做了一些研究,发现了一些关于分布条件类型的东西,但我不知道这是否真的是这里的问题,也无法找到解决方法.这里有没有办法保持类型安全,或者我的方法在概念上是错误的?