Can you explain the difference between these two generic types?
type FnWithRequiredParam<T> = (t: T) => void
type FnWithParamInferred = <T>(t: T) => void
From what I understand, FnWithRequiredParam
will always require the generic type to be explicitly defined. For example, using
FnWithRequiredParam<string>
will essentially turn it into (t: string) => void
.
However, I'm unclear on the meaning of FnWithParamInferred
. In some situations, <T>
is inferred based on its usage (such as with Array.map), but the following code snippet produces an error:
var f: FnWithParamInferred = (a: number) => { console.log(a) }
This error states that number
and T
are incompatible. So, what exactly is T
in this context? It hasn't been explicitly declared and is being compared to another type. How do function types like <T>(...) => ...
determine the generic T
?
It seems that when <T>
is a required generic of a class/interface, such as with Array<T>
, then methods of the array can successfully infer T
. However, outside of a class/interface, type inference doesn't appear to work the same way.