try 创建一个函数,其中(从类型的Angular 来看)基于前两个参数,它确定是否应该提供第三个参数.是否需要第三个参数取决于对象中是否存在特定的嵌套键(基于前两个参数的路径).我创造了一个人为的例子来演示:
type ExampleType = {
john: {
toolbox: { color: string }
},
jane: {
screwdriver: { color: string }
},
sally: {
hammer: { color: string },
nail: {}
}
}
type ColorArgs<Color> = Color extends never ? { color?: Color } : { color: Color };
type ExampleFn = <
Name extends Extract<keyof ExampleType, string>,
Thing extends Extract<keyof ExampleType[Name], string>,
Color extends (ExampleType[Name][Thing] extends { color: infer C } ? C : never)
>(config: { name: Name, thing: Thing } & ColorArgs<Color>) => string;
export const exampleFn: ExampleFn = ({ name, thing, color }) => {
console.log(name, thing, color);
return 'hello';
};
exampleFn({
name: 'sally',
thing: 'nail',
});
我希望函数能正常工作,并且当name是sally而thing是nail时不允许 colored颜色 参数.