Reputation: 123
type Id = <A>(a: A) => A
const id: Id = (a: number) => a;
If I use generics in this way the compiler will return an error saying
Type '(a: number) => number' is not assignable to type 'Id'.
Types of parameters 'a' and 'a' are incompatible.
Type 'A' is not assignable to type 'number'.
I know it can be solved with
type Id<A> = (a: A) => A
But what if I can't declare A at every point. Is there a way to just have it flow through, or be inferred?
Upvotes: 1
Views: 198
Reputation: 141512
I think what you're experiencing is the difference between these two type definitions.
type Func1<A> = (a: A) => A;
type Func2 = <A>(a: A) => A;
Any function of type Func1<A>
must specify its type at the time it is defined.
const func1: Func1<number> = (a: number): number => a;
func1(10); // works
func1("x"); // fails - we already decided it is of type `number`
Anything of type Func2
must not specify its type until it is called.
const func2: Func2 = <X>(a: X): X => a;
func2(10); // works
func2("x"); // works
Here is a playground link that illustrates.
The problem you were experiencing happened because you tried to specify the type of the function when you defined it instead of when you called it.
Upvotes: 2