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
I cannot use generic fn's Parameters when calling fn.
TypeScript Version: 3.9.2
Search Terms:
wrong generic function infer parameters
Code
constfunctionDict={A: (a: any)=>({ a }),B: (a: any,b: string)=>({ a, b }),C: (a: any,b: string,c: string)=>({ a, b, c }),};typeValueOf<T>=T[keyofT];exportfunctionfoo<FextendsValueOf<typeoffunctionDict>>(fn: F,pp: Parameters<F>,): void{fn(...pp);}
Expected behavior:
No error.
Actual behavior:
Error: Expected 3 arguments, but got 0 or more.(2556) input.ts(4, 9): An argument for 'a' was not provided
The generic constraint T extends X | Y does not mean "T extends X or T extends Y". It could be the case that T is X | Y, which extends neither X nor Y in general. Without a feature like #27808 there is no way in TypeScript to express a constraint of the form "T extends exactly_one_member_of X | Y".
In foo() the generic type F could turn out to be, for example, typeof functionDict.A | typeof functionDict.B:
constfn=Math.random()<0.5 ?
(a: any)=>({a: 123}) :
(a: any,b: string)=>({a: 123,b: b.toUpperCase()});foo(fn,["a"]);// 50% chance of "b is undefined" error
So it is technically unsound to allow fn(...pp) inside the function implementation without error. Of course, with some refactoring you could get the compiler to accept what you're doing inside the implementation:
functiongoo<Aextendsany[]>(fn: Extract<ValueOf<typeoffunctionDict>,(...a: A)=>any>,pp: A){fn(...pp);// okay}goo(fn,["a"]);// error at compile time now
but that's not exactly what you're looking for, I gather.
I cannot use generic
fn
'sParameters
when callingfn
.TypeScript Version: 3.9.2
Search Terms:
wrong generic function infer parameters
Code
Expected behavior:
No error.
Actual behavior:
Error:
Expected 3 arguments, but got 0 or more.(2556)
input.ts(4, 9): An argument for 'a' was not provided
Playground Link: https://www.typescriptlang.org/play/#code/MYewdgzgLgBAZgVzMKBLcARVKYF4YDeAsAFAzkwCCAXDABQCGtDYAngJR4B89BMDMAL7sANKQowAQrUbM2ImACNa0AE6owAc064edPgwWKho8RQDCMpv3lKVUdVoXB7j7d178jzk2JKCAblJSKFYABwBTGAA1BgAbBAiAeTgAHgAVHnx0gG0AawjWEDgYdIBdIJJSCIAPMJBVWERkNHB4EBBUgDEYWqgIsAATCBj4xJTU0Mji+CQUdDAsFC4uOjNyODBaLr8JMLDaAAUGVQYAWwj+1Qhurj92WgA3EFRBwnX4MDoAOl-99kqglIQA
Related Issues:
The text was updated successfully, but these errors were encountered: