10

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

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

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

Is there any way to do it?

1 Answer 1

10

In your last snippet:

type A = <T>(value: T) => T;
const a: A = value => value;

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;

You can also do this:

type A<T> = (value: T) => T;
const a: A<string> = value => value;

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

5 Comments

So, the clear callback that is not specific without parenthesis is not allowed, right?
It is allowed, you're not getting any errors right?
Well, except the value becames any, and it is not allowed by my tsconfig.json. Anyway, thank you, the answer helped me.
What version of typescript does this work with? I am on the typescript playground and your solution still shows errors. I have tried down to version 3.3, and they all show errors...
@smac89 yeah, getting errors as well. based on the date of the answer i'd say that it was using version 2.2

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.