822

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?

18 Answers 18

1174

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;
Sign up to request clarification or add additional context in comments.

13 Comments

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?
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.
Newer typescript compilers also support trailing comma const foo = <T,>(x: T) => x; to sidestep the JSX ambiguity.
@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
how to set default generic type? const foo = <T = any,>(x: T) => x not work, i always get unknown
|
364

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 Comments

Do they plan to fix this behavior?
I guess there is not much that could be done about this... the JSX and Typescript generic syntaxes just clash here..
What about default type parameter type? const foo = <T = any,>(x: T) => x doesn't work...
Why does this hack work? what is the comma saying in this case?
@w4tson if you had two generics, you could write <T, F>... apparently you can omit the second..
|
118

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

1 Comment

While it works nicely, I must say that it does look like a bit of a hack...
64

This works for me

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

4 Comments

If In .ts file this works. Otherwise one has to extend.
Works perfectly fine: typescript-play.js.org/#code/…
this is working fine for me in .ts and .tsx files in vscode
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
52

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

Comments

27

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 Comments

This does not work for me, I have to add a comma like so: <T, >. as described in @Thomas comment under @jbmilgrom' answer
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.
doesn work, as doesn't a comma. Syntax error caught by VSCode
24

This works for me

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

2 Comments

But this was already suggested many times
if you have nothing own to say then you have to copy/paste someones work :P
14

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;

2 Comments

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.
Supposedly <T,> works just fine as part of the function definition but <T> does not. Honestly I don't have time to look into why right now so I'll accept it for what it is....
13

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

Comments

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;

Comments

7

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

Comments

4
type TypeCbFoo = <T>(x: T) => T;
const foo: TypeCbFoo = (x) => x;

with useCallback

const foo2 = useCallback<TypeCbFoo>((x) => x, []);

inline

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

Comments

2

In 2021, Ts 4.3.3

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

1 Comment

move => 1 line above if u want
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;
    ...
};

Comments

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

2 Comments

The advantage of the comma in the other answer is because this will break if you have TSX (React) code.
This answer has been provided before.
-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

Comments

-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

Comments

-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!

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.