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
This is the right behaviour. The generic parameter T is rigid inside the definition of the function so it won’t pick up inferences. It’s better to think of T as a fixed, but unknown type; you can’t just assign a number to it.
If you want type inference you should leave type annotation off the declaration of the function.
the idea is to let getA() to take any function so long as it's compliant to the generic interface. If I leave out the signature of getA(), it basically became "fixed" after the first assignment:
interfaceA<T>{foo: T;}consta: A<number>={foo: 13};//let getA: <T>() => A<T> = () => a; letgetA=()=>a;constb: A<string>={foo: "13"};getA=()=>b;// <== now error here
this is a common pattern that a system assigned a default initial value/logic but later refined with actual implementation that are not known at compile time other than the generic interface they are conformed... maybe there are other ways to accomplish this?
You want an existential type. You've written that getA has a universal (generic) type.
The easiest way would be to make getA: () => A<unknown>, because that's all that it could be used as. If the caller doesn't know what type they'll get out, then unknown is the best you can do (in most circumstances- if the parameter is used contravariantly you'd want never instead, I guess).
TypeScript Version: 3.3.1
Search Terms: generic function assignment, generic type infer
Code
Expected behavior:
no compile error
Actual behavior:
compile error:
Playground Link: here
Related Issues:
#17574
#26871
The text was updated successfully, but these errors were encountered: