#Generics Syntax
6 messages · Page 1 of 1 (latest)
There's some discussion of it in the handbook - https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-types - the first one is a generic function, stored in a type, the second is a generic type which describes a (ultimately, non-generic) function
The handbook example is essentially:
type Identity1 = <T>(x: T) => T;
type Identity2<T> = (x: T) => T
And the first one is a type describing a generic function: Identity1 is a function can take any input and returns the same type out.
Identity2 can be thought of as a type that builds a single type of function, Identity<string> results in a (x: string) => string function, not a generic function
In practice, it comes down to when you want to provide the type; usually your usage will force one version or the other. I tend to find the Identity2 style a lot more common - not that generic functions aren't common, but it's somewhat rare that you put them in type aliases.
what are the usage cases that fore one or the other?
TBH, I have a hard time coming up with practical examples of the first one. I'm sure they exist, I just can't really come up with any. The second pattern gets used a fair bit though - e.g. React exposes a type that's like this:
type SetState<T> = (
val: T | ((oldVal: T) => T)
) => void
which is sometimes used for props like:
type MyProps = {
name: string,
setName: SetState<string>
}