Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a generic type for an arrow function in Typescript

I try to write typescript functions in the style that is most close to functional. For simple functions I can write:

type A = (value: number) => string;
const a: A = value => value.toString();

But what can I do with generic types? How can I type in that simple way following function?

function a<T>(value: T): T {
  return value;
}

If I try to simply add a generic type, it gives nothing:

type A = <T>(value: T) => T;
const a: A = value => value; // `value` implicitly has an `any` type

Is there any way to do it?

like image 619
Lodin Avatar asked Jan 26 '17 14:01

Lodin


People also ask

How do I create a generic type in TypeScript?

Assigning Generic ParametersBy passing in the type with the <number> code, you are explicitly letting TypeScript know that you want the generic type parameter T of the identity function to be of type number . This will enforce the number type as the argument and the return value.

How do I add a return type in TypeScript for arrow function?

You can set the return type of an arrow function in TypeScript right after its parameters, e.g. const greet = (name: string): string => {} . Once a function's return type is set, the type checker alerts us if the function returns a value of a different type.

What is generic in TypeScript?

Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use. Generics makes it easier to write reusable code.

Does TypeScript have generics?

TypeScript supports generic classes. The generic type parameter is specified in angle brackets after the name of the class. A generic class can have generic fields (member variables) or methods.


1 Answers

In your last snippet:

type A = <T>(value: T) => T;
const a: A = value => value;

You tell the compiler that a is of type A, but you don't bind it to a specific generic type which is why it uses any.

For example, you can set the generic type like so:

const a: A = (value: string) => value;

You can also do this:

type A<T> = (value: T) => T;
const a: A<string> = value => value;

If you want a to be specific.

If you want a to stay generic you'll need to declare the generic constraint on it as well:

const a: A = <T>(value: T) => value;
like image 182
Nitzan Tomer Avatar answered Oct 09 '22 12:10

Nitzan Tomer