Home > Enterprise >  How to explain this construct in typescript?
How to explain this construct in typescript?

Time:06-02

I am learning ts, and I have stumbled upon this piece of code

export const Field:<T> (x:T) => T;

I can't wrap my head around it.

It does look like the function definition below

type myFunction<T> = (x: T) => T

so I would see it as anonymous type definition but am I correct, how to use it?

CodePudding user response:

This:

<T>(x: T) => T

Is the type of an identity function. It uses a generic type parameter T set by the type of the argument x, and returns an object of type T. Or more simply, it returns the type that it received as an argument.

The javascript implementation would be simply:

(x) => x

To implement that type in Typescript, you might do:

const fn: Field = <T>(x: T) => x

Playground

  • Related