TypeScript函数类型联合为何将输入按交叉类型合并?求解法
问题分析与解决方案
函数联合参数变成交叉类型的原因
TypeScript里函数类型的联合遵循逆变规则:当你把多个函数类型用|联合时,它们的参数类型会自动变成交叉类型(&)。这是因为TypeScript要保证传入的参数能被联合里的任意一个函数安全调用——只有同时满足所有函数的参数要求,才能不管fn是联合里的哪一个,都不会出错。所以你定义的allowedFns是两个函数的联合,TypeScript就会认为fn的参数必须同时是{A: string}和{B: number},也就是交叉类型,这才导致了报错。
原始问题的解决
要让fn和input的类型严格对应,别用联合类型直接定义,改用泛型绑定函数和它的参数:
type AllowedFn = | ((obj: { A: string }) => any) | ((obj: { B: number }) => any); const caller = <T extends AllowedFn>(fn: T, input: Parameters<T>[0]) => { return fn(input); }; // 正常调用 caller((obj: {A: string}) => obj.A, {A: "测试"}); caller((obj: {B: number}) => obj.B, {B: 123}); // 参数不匹配时会报错,符合预期 caller((obj: {A: string}) => obj.A, {B: 456});
补充代码的问题与修复
你用对象存函数、通过泛型关联键名的思路没问题,但当前代码TypeScript没法自动推断泛型fnName,导致input和fn的类型没绑定上。给fns加个as const让TypeScript保留精确的函数类型就行:
const fn1 = (input: { A: string }) => input.A; const fn2 = (input: { B: number }) => input.B; // as const 让TypeScript不宽泛推断,保留每个函数的精确类型 const fns = { fn1, fn2 } as const; type AllowedFns = keyof typeof fns; const caller = <K extends AllowedFns>( fn: typeof fns[K], input: Parameters<typeof fns[K]>[0] ) => { return fn(input); }; // 正常调用 caller(fns.fn1, {A: "hello"}); caller(fns.fn2, {B: 456}); // 参数不匹配时报错,符合预期 caller(fns.fn1, {B: 789});
也可以不用键名,直接让泛型绑定函数类型,写法更简洁:
const caller = <T extends typeof fns[keyof typeof fns]>( fn: T, input: Parameters<T>[0] ) => { return fn(input); }; // 同样能正常调用 caller(fn1, {A: "测试"}); caller(fn2, {B: 123});
内容的提问来源于stack exchange,提问作者Lucas Mumbo
相关产品推荐
相关产品推荐

