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?
Assigning Generic ParametersBy passing in the type with the <number> code, you are explicitly letting TypeScript know that you want the generic type parameter T of the identity function to be of type number . This will enforce the number type as the argument and the return value.
You can set the return type of an arrow function in TypeScript right after its parameters, e.g. const greet = (name: string): string => {} . Once a function's return type is set, the type checker alerts us if the function returns a value of a different type.
Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use. Generics makes it easier to write reusable code.
TypeScript supports generic classes. The generic type parameter is specified in angle brackets after the name of the class. A generic class can have generic fields (member variables) or methods.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With