Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to explain this construct in typescript?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading