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;
Answer from jbmilgrom on Stack OverflowEdit
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;
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.
Cannot define an arrow function with a single generic type parameter that has a default value with JSX
Generic parameter in arrow function in .tsx file causes an error
How to return a generic type from a function?
typescript - why generic type arrow function shows error? - Stack Overflow
Videos
For example, in typescript I create a function that returns a generic arrow function with a declaration that can look something like this:
function foo(someOtherValue: any): <U>(value: U) => U | undefined {
return <U>(value: U) => U | undefined {
return someOtherValue === value ? value : undefined;
};
}However, I would like to have a generic type that represents the above generic arrow function and have it being returned... Something like this:
type FooRet<U> = (value: U) => U | undefined;
function foo(someOtherValue: any): <U>FooRet<U> {
return <U>(value: U) => U | undefined {
return someOtherValue === value ? value : undefined;
}
}Obviously the above doesn't compile, hence my question. I tried to look it up online, but I'm not sure how to describe my problem to get the answer I'm looking for... Sorry if this has been answered already.