ChatGPT解决这个技术问题 Extra ChatGPT

What is the syntax for Typescript arrow functions with generics?

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?


j
jbmilgrom

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;

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
So is this the takeaway: "use .ts instead of .tsx extensions"?
m
mb21

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.


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..
Fantastic - this is by far the best answer: works perfectly and doesn't alter the behaviour at all!
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?
k
k0pernikus

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

"T extends any" would then support void.
While it works nicely, I must say that it does look like a bit of a hack...
H
Harshit Singhai

This works for me

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

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
A
Andreas Frische

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

your example is too complicated, that's why similar one from Harshit Singhai gets more votes
B
Bear

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)

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
c
const.takeo

This works for me

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

But this was already suggested many times
M
Michal Filip

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;

R
Roy Art

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;

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.
L
LearnToLive

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

} 

C
CodeFarmer

In 2021, Ts 4.3.3

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

move => 1 line above if u want
E
Ester Kaufman

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

N
Nkoro Joseph Ahamefula

https://i.stack.imgur.com/LuzEI.png

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.

https://i.stack.imgur.com/cTthY.png


Y
Yuh Lee

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!