Typescript generic type bound to a function Vs Type bound to a generic function

Viewed 22

I'm a little confused with some generic behaviour in TS. With this code in a d.ts file, with TS 4.0.2

type GetValueFn = <T>(obj: T) => number;
export const getAverageValue: <T>(input: T[], getValue: GetValueFn<T>) => number;

On the second line the compiler complains that GetValueFn type is not generic.

If i write it like that (notice the <T> moved from right side to left side of assignment on first line).

type GetValueFn<T> = (obj: T) => number;
export const getAverageValue: <T>(input: T[], getValue: GetValueFn<T>) => number;

The compiler is happy, i have a generic type.

Now, with this code :

type ComparatorFn<T> = (a: T, b: T) => number;
type ElementGetFn<T> = (input: T[], comparator: ComparatorFn<T>) => T;

Written with the <T> on the left side.

If i try to use the types like this :

export const getMaxElement: ElementGetFn;
export const getMinElement: ElementGetFn;

This time TS complains that ElementGetFn requires 1 type argument (!?)

If i then rewrite the ElementGetFn declaration like this (with the <T> on the right side)

type ElementGetFn = <T>(input: T[], comparator: ComparatorFn<T>) => T;

Now the compiler is happy.

What am i missing ?

0 Answers
Related