I'm trying to learn typescript generics, but couldn't understand the difference between these two types:
type A<T> = (x: T) => T;
type B = <T>(x: T) => T;
I only found one video on yt, but unfortunately this wasn't enough to make my brain understand...
Does any1 have a simple explanation? Thanks!
CodePudding user response:
With type A<T> = (x: T) => T;
the generic has to be passed when using the type, for example:
// here a is (c: string) => string;
let a: A<string> = x => x;
// a only accept string
a('foo')
With type B = <T>(x: T) => T;
the generic is passed when the function is called:
// no generic yet
let b: B = x => x;
// here b is (x: number) => number;
b<number>(42);
// here b is (x: boolean) => boolean;
b<boolean>(true);
// you can omit the generic since TS will infer it
// here b is (x: string) => string;
b('hello')