Home > Net >  Separating generic type definition of function in TypeScript?
Separating generic type definition of function in TypeScript?

Time:02-24

For instance, in Haskell, having corresponding standalone definitions for each type and function is the standard way to define a function.

The definition of id in Haskell is:

id :: forall a. a -> a
id = \a -> a

In TypeScript, we can write

const id = <T>(a: T) => a;

but often, I want to define similarly in the manner of Haskell.

type id<T> = (a:T) => T 
const id:id<T> = a => a;

This generates an error: Cannot find name 'T'.ts(2304)

Please note:

I know the code below works,

type id<T> = (a: T) => T
const id: id<number> = a => a;

but my Question is for

const id = <T>(a: T) => a;

Is there any proper way to write in the separation manner?

TypeScript Version 4.5.5

CodePudding user response:

type id = <T>(a: T) => T
const id: id = a => a;
  • Related