-
Notifications
You must be signed in to change notification settings - Fork 12.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Function overload requires an if statement for TS to parse argument types correctly #54027
Comments
Duplicate of #40827. |
This is a single call signature with a union type for the arguments so it's not actually an overload. This is closer to #32639; the type system can't form a dependent narrowing relationship between const myFunc4 = (...args: MyFunc) => {
myFunc(...args);
} |
Thanks all for the pointers and @nmain for the cool workaround, very interesting that not destructuring would make it work 👍 nit: I should have named |
@xitanggg Basically the destructured version fails because the compiler is only looking at the types of values individually, it doesn’t track “where they came from” (a By not destructuring, you keep a |
Thanks for the explanation @fatcerberus. Right, this seems like a TS limitation as it doesn't try to loop through the options of the defined call signature. My actual use case is slightly more complex with a function that has a call signature of an array union calling another function that has a call signature of an object union. It seems it would have to destructure to create the object with no easy workaround type MyFuncObjArgs =
| {
arg1: string;
arg2: string;
}
| { arg1: boolean; arg2: boolean };
const myFuncObj = (args: MyFuncObjArgs) => {};
type MyFuncArrayArgs =
| [arg1: string, arg2: string]
| [arg1: boolean, arg2: boolean];
const myFunc = (...[arg1, arg2]: MyFuncArrayArgs) => {
// Have to destructure here to create an object, but Typescript yells
myFuncObj({ arg1, arg2 });
}; |
@RyanCavanaugh talks about that often - in general, if something can only be proven safe through manual enumeration of the possibilities, the compiler is most likely going to reject it. Type safety has to be provable “in the abstract”, so to speak. |
🔎 Search Terms
Function overload
🕗 Version & Regression Information
This is the behavior in every version I tried starting at 4.x, as well as the nightly version
⏯ Playground Link
Playground link with relevant code
💻 Code
🙁 Actual behavior
TS throws an error for
myFunc2
because it thinks arg1 can be bothstring
orboolean
but it should only be either one.🙂 Expected behavior
TS should not throw an error for
myFunc2
The text was updated successfully, but these errors were encountered: