#Generics Syntax

6 messages · Page 1 of 1 (latest)

worn axle
#

Can someone help me understand the difference between these 2? The first one works correctly but I realized the second one is valid and I don't know what that syntax would do.

export type Foo = <S extends Bar>(s: S) => Thing<S>;
export type Foo<S extends Bar> = (s: S) => Thing<S>;
bronze lava
#

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.

worn axle
#

what are the usage cases that fore one or the other?

bronze lava
#

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>
}