How to create a generic type for an arrow function in Typescript

Lod*_*din 5 generics typescript typescript-typings

I try to write typescript functions in the style that is most close to functional. For simple functions I can write:

type A = (value: number) => string;
const a: A = value => value.toString();
Run Code Online (Sandbox Code Playgroud)

But what can I do with generic types? How can I type in that simple way following function?

function a<T>(value: T): T {
  return value;
}
Run Code Online (Sandbox Code Playgroud)

If I try to simply add a generic type, it gives nothing:

type A = <T>(value: T) => T;
const a: A = value => value; // `value` implicitly has an `any` type
Run Code Online (Sandbox Code Playgroud)

Is there any way to do it?

Nit*_*mer 6

In your last snippet:

type A = <T>(value: T) => T;
const a: A = value => value;
Run Code Online (Sandbox Code Playgroud)

You tell the compiler that a is of type A, but you don't bind it to a specific generic type which is why it uses any.

For example, you can set the generic type like so:

const a: A = (value: string) => value;
Run Code Online (Sandbox Code Playgroud)

You can also do this:

type A<T> = (value: T) => T;
const a: A<string> = value => value;
Run Code Online (Sandbox Code Playgroud)

If you want a to be specific.

If you want a to stay generic you'll need to declare the generic constraint on it as well:

const a: A = <T>(value: T) => value;
Run Code Online (Sandbox Code Playgroud)

  • 这适用于什么版本的打字稿?我在打字稿游乐场上,你的解决方案仍然显示错误。我已经尝试过3.3版本,但它们都显示错误...... (2认同)
  • @smac89 是的,也出现错误。根据答案的日期,我会说它使用的是版本“2.2” (2认同)