What is the syntax for Typescript arrow functions with generics?

Typescript

Typescript Problem Overview


The typescript handbook currently has nothing on arrow functions. Normal functions can be generically typed with this syntax: example:

function identity<T>(arg: T): T {
    return arg;
}

What is the syntax for arrow functions?

Typescript Solutions


Solution 1 - Typescript

Edit

Per @Thomas comment, in newer TS compilers, we can simply do:

const foo = <T,>(x: T) => x;

Original Answer

The full example explaining the syntax referenced by Robin... brought it home for me:

Generic functions

Something like the following works fine:

function foo<T>(x: T): T { return x; }

However using an arrow generic function will not:

const foo = <T>(x: T) => x; // ERROR : unclosed `T` tag

Workaround: Use extends on the generic parameter to hint the compiler that it's a generic, e.g.:

const foo = <T extends unknown>(x: T) => x;

Solution 2 - Typescript

If you're in a .tsx file you cannot just write <T>, but this works:

const foo = <T, >(x: T) => x;

As opposed to the extends {} hack, this hack at least preserves the intent.

Solution 3 - Typescript

I found the example above confusing. I am using React and JSX so I think it complicated the scenario.

I got clarification from TypeScript Deep Dive, which states for arrow generics:

Workaround: Use extends on the generic parameter to hint the compiler that it's a generic, this came from a simpler example that helped me.

    const identity = < T extends {} >(arg: T): T => { return arg; }

Solution 4 - Typescript

This works for me

const Generic = <T> (value: T) => {
    return value;
} 

Solution 5 - Typescript

The language specification says on p.64f

> A construct of the form < T > ( ... ) => { ... } could be parsed as an > arrow function expression with a type parameter or a type assertion > applied to an arrow function with no type parameter. It is resolved as > the former[..]

example:

// helper function needed because Backbone-couchdb's sync does not return a jqxhr
let fetched = <
           R extends Backbone.Collection<any> >(c:R) => {
               return new Promise(function (fulfill, reject) {
                   c.fetch({reset: true, success: fulfill, error: reject})
               });
           };

Solution 6 - Typescript

so late, but with ES6 no need extends it still work for me.... :)

let getArray = <T>(items: T[]): T[] => {
    return new Array<T>().concat(items)
}

let myNumArr = getArray<number>([100, 200, 300]);
let myStrArr = getArray<string>(["Hello", "World"]);
myNumArr.push(1)
console.log(myNumArr)

Solution 7 - Typescript

This works for me

 const logSomething = <T>(something:T): T => {
       return something;
    }

Solution 8 - Typescript

while the popular answer with extends {} works and is better than extends any, it forces the T to be an object

const foo = <T extends {}>(x: T) => x;

to avoid this and preserve the type-safety, you can use extends unknown instead

const foo = <T extends unknown>(x: T) => x;

Solution 9 - Typescript

I to use this type of declaration:

const identity: { <T>(arg: T): T } = (arg) => arg;

It allows defining additional props to your function if you ever need to and in some cases, it helps keeping the function body cleaner from the generic definition.

If you don't need the additional props (namespace sort of thing), it can be simplified to:

const identity: <T>(arg: T) => T = (arg) => arg;

Solution 10 - Typescript

I know I am late to this answer. But thought of answering this in case anyone else finds it helpful. None of the answers mention how to use generics with an async arrow function.

Here it goes :

const example = async <T> (value: T) => {
    //awaiting for some Promise to resolve or reject;
     const result = await randomApi.getData(value);

} 

Solution 11 - Typescript

In 2021, Ts 4.3.3

const useRequest = <DataType, ErrorType>(url: string): Response<DataType, ErrorType> 
   => {
      ...
   }

Solution 12 - Typescript

Adding an example for multiple depended generic types:

This function, was converted to arrow function as the following:

http.get = function <T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R> {
            config.withCredentials = true;
            ....
          };

Notice the extends instead of the equal sign:

http.get = async <T extends any, R extends unknown = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R> => {
            config.withCredentials = true;
            ...
          };

Solution 13 - Typescript

enter image description here

Using throws an error when you try to pass null as parameter. I will prefer using because it clears the issue. I am yet to get the reason why. But this worked for me.

enter image description here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndreas FrischeView Question on Stackoverflow
Solution 1 - TypescriptjbmilgromView Answer on Stackoverflow
Solution 2 - Typescriptmb21View Answer on Stackoverflow
Solution 3 - TypescriptRobin LuitenView Answer on Stackoverflow
Solution 4 - TypescriptHarshit SinghaiView Answer on Stackoverflow
Solution 5 - TypescriptAndreas FrischeView Answer on Stackoverflow
Solution 6 - TypescriptBearView Answer on Stackoverflow
Solution 7 - Typescriptconst.takeoView Answer on Stackoverflow
Solution 8 - TypescriptMichal FilipView Answer on Stackoverflow
Solution 9 - TypescriptRoy ArtView Answer on Stackoverflow
Solution 10 - TypescriptLearnToLiveView Answer on Stackoverflow
Solution 11 - TypescriptCodeFarmerView Answer on Stackoverflow
Solution 12 - TypescriptEster KaufmanView Answer on Stackoverflow
Solution 13 - TypescriptNkoro Joseph AhamefulaView Answer on Stackoverflow