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
Inconsistent function argument type inference based on result assignment wayΒ #59781
declarefunctionfirst(b: 1): 11;declarefunctionsecond(a: 2): 22;declarefunctionexecute<Textendsreadonlyunknown[]>(functions: T,data: Arguments<T>): Returns<T>;const[a,b]=execute([first,second],[1,2]);// okconstresult=execute([first,second],[1,2]);// err: Type 'number' is not assignable to type 'undefined'typeReturns<Textendsreadonlyunknown[]>={[KinkeyofT]: T[K]extends(...args: any[])=> infer R ? R : never;};typeArguments<Textendsreadonlyunknown[]>={[KinkeyofT]: T[K]extends(arg: infer R)=>unknown ? R : never;};
π Actual behavior
Type inference works differently with destructuring assignment compared to regular assignment.
π Expected behavior
Type inference shouldn't be affected by assignment way.
Additional information about the issue
I know the types for execute function are not right, but its irrelevant.
TS has to decide how to treat your array literal. It doesn't know if its type should be a tuple type or an array type so it uses contextual information to decide this. The binding pattern is such information here and thanks to it it infers/assigns a tuple type to your first argument. The other example has no such information so it defaults to an array type.
You can fix this by hinting TS that you want tuples here like this:
Activity
Andarist commentedon Aug 28, 2024
TS has to decide how to treat your array literal. It doesn't know if its type should be a tuple type or an array type so it uses contextual information to decide this. The binding pattern is such information here and thanks to it it infers/assigns a tuple type to your first argument. The other example has no such information so it defaults to an array type.
You can fix this by hinting TS that you want tuples here like this:
There are also other ways to hint this but I find this one to be the most idiomatic one.
AjiTae commentedon Aug 28, 2024
But should it really behave this way? It's incredibly confusing on a deeper, intuitive js level.:)
Andarist commentedon Aug 28, 2024
Itβs by design: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-8.html#improved-inference-from-binding-patterns