New to TypeScript and get your head to understand what Generics do? This short article if for you.
Generics?
Generics is simply a way to build code components that work with different data types without losing information about that data type. Such components are reusable; they can take in an input of any data type and produce the required output. This allows the component to be flexible.
Without Generics
Here is a TypeScript functions that echos out whatever it's given. without applying the generic method, you'd have to specify the type of the argument or use the any
type.
// Specific type
function echo(arg: number): number {
return arg
}
// Using the 'any' type
function echo(arg: any): any {
return arg
}
Using specific types will only hold information about that type. Using the 'any' type seems generic but it loses information about the type of data passed in. If you pass a string with a type of 'any,' Typescript will translate the returned type as 'any'; not a string.
The Generic Way
The generic way would be to capture the argument despite the type and denote what is being returned. The 'Type' variable does that. it's a special variable for data type rather than values.
// Using the 'Type' variable
function echo<Type>(arg: Type): Type {
return arg;
}
The 'Type' variable captures a range of types and holds the information for later use thus making the 'echo' function generic.
Calling Generic Functions
A generic function can be called in two ways. The first is to pass the 'Type' variable argument and the function. This way you explicitly set 'Type' to be a string.
let output = echo<string>("Romeo");
The second way is by calling the function and only passing the argument. Typescript will infer the types automatically for you.
let output = echo("Romeo");
Always use the first way when working on complex code because TypeScript may fail to infer the proper type.
The End
Now you know the 101 of TypeScript Generics. Cheers!
Top comments (0)