You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Generic inference of Overloaded methods only working with the last defined methodΒ #43187
classSomeClazz{publicoverload(param: 'PARAM1'): number;publicoverload(param: 'PARAM2'): string;publicoverload(param: 'PARAM1'|'PARAM2'): number|string{switch(param){case'PARAM1':
return1337;case'PARAM2':
return'Hi';}}}functioncall<Ctxextends{[FinName]: (this: Context, ...args: any[])=>any},Nameextendsstring>(ctx: Ctx,method: Name,
...args: Parameters<Ctx[Name]>): void{ctx[method](...args);}constclazz=newSomeClazz();clazz.overload('PARAM1');// Works okclazz.overload('PARAM2');// works okcall(clazz,'overload','PARAM1');// ERROR: Argument of type '"PARAM1"' is not assignable to parameter of type '"PARAM2"'call(clazz,'overload','PARAM2');// Works ok
Type inference in conditional types, such as Parameters<T>, does not work with overloads. In this case the last signature is used, as you noticed. This is a design limitation and is mentioned in the docs.
edit:
My bad. The documentation that mentioned this behavior (Advanced Types) has officially been deprecated, and the new documentation does not mention this limitation at all (I've created a PR).
When inferring from a type with multiple call signatures (such as the type of an overloaded function), inferences are made from the last signature (which, presumably, is the most permissive catch-all case). It is not possible to perform overload resolution based on a list of argument types.
Note that there are no conditional types in this example; the particular limitation here is for generic type parameter inference, (which has the same problem of course).
Activity
MartinJohns commentedon Mar 11, 2021
Type inference in conditional types, such as
Parameters<T>, does not work with overloads. In this case the last signature is used, as you noticed. This is a design limitation and is mentioned in the docs.edit:
My bad. The documentation that mentioned this behavior (Advanced Types) has officially been deprecated, and the new documentation does not mention this limitation at all (I've created a PR).
jcalz commentedon Nov 17, 2021
Note that there are no conditional types in this example; the particular limitation here is for generic type parameter inference, (which has the same problem of course).
rpeszek commentedon Apr 9, 2022
It should be noted that this could cause the code to be brittle. Changing ordering of overloads is likely to result in compilation breaking.
This is likely to happen with office.js which has a quite complex overloaded design.
I have implemented an example inspired by office.js here:
https://github.com/rpeszek/typescript-issues/blob/master/src/RejectingCorrectCode/RejectingOverloads.ts