701

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?

16 Answers 16

999

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;
13
  • 16
    would it be possible to declare some predefined generic type for const foo? i.e. type GenericFun<T, A=T> = (payload: A) => T; then make const foo: GenericFun still generic without providing a T type?
    – ciekawy
    Feb 28, 2018 at 1:04
  • 40
    Your second example is only an error in a .tsx file (TypeScript + JSX). In a .ts file it works fine, as you can see on the TypeScript playground.
    – danvk
    Jan 17, 2019 at 13:53
  • 248
    Newer typescript compilers also support trailing comma const foo = <T,>(x: T) => x; to sidestep the JSX ambiguity.
    – Thomas
    May 21, 2019 at 16:54
  • 6
    @danvk Worth noting this only holds true for those who have forbidden JSX in TS files - if a project is configured to allow JSX in TS files you'll still need the "extends" or the trailing comma
    – Matt
    Nov 19, 2019 at 21:24
  • 4
    how to set default generic type? const foo = <T = any,>(x: T) => x not work, i always get unknown
    – Enivia
    Mar 10, 2021 at 3:39
333

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.

8
  • 2
    Do they plan to fix this behavior? Mar 26, 2020 at 7:20
  • I guess there is not much that could be done about this... the JSX and Typescript generic syntaxes just clash here..
    – mb21
    Mar 29, 2020 at 12:53
  • 13
    What about default type parameter type? const foo = <T = any,>(x: T) => x doesn't work... May 31, 2020 at 21:40
  • 12
    Why does this hack work? what is the comma saying in this case?
    – w4tson
    Sep 30, 2020 at 7:01
  • 1
    @w4tson if you had two generics, you could write <T, F>... apparently you can omit the second..
    – mb21
    Sep 30, 2020 at 7:12
111

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; }
2
  • 13
    "T extends any" would then support void. May 4, 2018 at 15:56
  • While it works nicely, I must say that it does look like a bit of a hack...
    – natiiix
    Dec 10, 2020 at 19:44
59

This works for me

const Generic = <T> (value: T) => {
    return value;
} 
4
  • 23
    If In .ts file this works. Otherwise one has to extend.
    – HalfWebDev
    Aug 10, 2019 at 9:27
  • 2
    Works perfectly fine: typescript-play.js.org/#code/…
    – Alireza
    Dec 16, 2019 at 10:10
  • this is working fine for me in .ts and .tsx files in vscode
    – Shubhan
    May 15, 2020 at 10:18
  • 2
    JSX element 'T' has no corresponding closing tag.ts(17008) Cannot find name 'T'.ts(2304) does NOT work in tsx files for me in vs code
    – JesseBoyd
    Aug 5, 2022 at 20:23
51

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})
               });
           };
0
26

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)
3
  • 5
    This does not work for me, I have to add a comma like so: <T, >. as described in @Thomas comment under @jbmilgrom' answer
    – apollo
    Jun 7, 2020 at 21:40
  • 3
    You should read the other solutions before posting one. Your solution has already been posted with explanation. It works only inside of a .ts file, not a .tsx file.
    – Isaac Pak
    Jun 26, 2020 at 20:55
  • doesn work, as doesn't a comma. Syntax error caught by VSCode
    – trainoasis
    Jan 14, 2022 at 16:17
22

This works for me

 const logSomething = <T>(something:T): T => {
       return something;
    }
1
  • 4
    But this was already suggested many times
    – Vega
    Aug 11, 2021 at 11:30
12

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;
0
10

I 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 keep 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;
1
  • When using <T> inside the function body, this did not work for me. Typescript tells me <T> isn't used for the <T> at the function definition location and tells me that it cannot find <T> at the position where I refer to it in the function body. With the <T,> 'hack' I do not have this issue.
    – Martijn
    Jan 19, 2022 at 15:14
7

The non-arrow function way. Expanding on the example from the OP.

function foo<T>(abc: T): T {
    console.log(abc);
    return abc;
}

const x = { abc: 123 };
foo(x);

const y = 123;
foo<number>(y);

Aside from the answer of embedding the whole thing into one statement:

const yar = <T,>(abc: T) => {
    console.log(abc);
    return abc;
}

Another approach is to have an intermediate type:

type XX = <T>(abc: T) => T;

const bar: XX = (abc) => {
    console.log(abc);
    return abc;
}

Playground

4

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);

} 
2

In 2021, Ts 4.3.3

const useRequest = <DataType, ErrorType>(url: string): Response<DataType, ErrorType> 
   => {
      ...
   }
1
  • move => 1 line above if u want
    – CodeFarmer
    Jul 15, 2021 at 6:45
2

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;
            ...
          };
-2

enter image description here

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

enter image description here

-3

Here I got 2 cases of arrow function with generics:

  • To call directly:
const foo = <T>(value: T): void => {
    console.log(value);
foo('hello') // hello
}
  • To create a type to use later:
type TFoo<S> = (value: S) => boolean;
const foo: TFoo<number> = (value) => value>0;
console.log(foo(1)) // true
console.log(foo(-1)) // false

Hopefully this helps somewhere!

-3

If need make return method generic, it didn't show errors with extra data ex:

export type DataGenerator<T> = (props: {name: string}) => T;

const dataGenerator: DataGenerator<{city?: string}> = ({  name }) => {
    return {
        city: `${name}`,
        name: "aaa",
    }
}

dataGenerator({name: "xxx"})

I need to show error on name

1
  • 3
    This is not an answer to the question.
    – kaya3
    Apr 13 at 1:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.