What's the different between these two `type` define which have different generic place, and how to use them?

41 Views Asked by At

I found 2 different type like:

  1. type Pair = <Head, Tail> (head: Head) => (tail: Tail) => {head: Head; tail: Tail;}
  2. type Pair <Head, Tail> = (head: Head) => (tail: Tail) => {head: Head; tail: Tail;}

The only diff is <Head, Tail>'s place.

They're both legal but different while be use.

Such as:

When I define a function pair, I can use the first type define like this:

type Pair = <Head, Tail> (head: Head) => (tail: Tail) => {head: Head; tail: Tail;} ;

const pair: Pair = <Head, Tail> (head: Head) => (tail: Tail) => ({head, tail}) ;
const result = pair (1) ("two") ;

console.log(result); // {head: 1, tail: "two"}

But when I want to use the second type define on pair, I can only write that:

type Pair <Head, Tail> = (head: Head) => (tail: Tail) => {head: Head; tail: Tail;} ;

const pair: Pair<number, string> = <Head, Tail> (head: Head) => (tail: Tail) => ({head, tail}) ;
const result = pair (1) ("two") ;

console.log(result); // {head: 1, tail: "two"}

But that should not called pair, we should call it number_string_pair at least, but this is not what I want.

Use TypeScript v5.2.2, Here is the test.


To be honest, I want to know how can I use the second type Pair define to pair's type sign, but I can't find it, so I asked this question ...

And, I want to know what the first type Pair mean ... I know about what type Fn <X, Y> = (x: X) => Y mean, the Fn<number, string> will same as (x: number) => string, but if I defined type Fn = <X, Y> (x: X) => Y, I can't use it like Fn<number, string> ... so, what's the use of the second type Fn or first type Pair and what's the meaning of them ?

0

There are 0 best solutions below