What are Generics in TypeScript ?
Last Updated :
14 Mar, 2022
In this article, we will try to understand all the facts as well as the details associated with Generics in TypeScript along with some coding examples.
Generics in TypeScript:
- Whenever any program or code is written or executed, one major thing one always takes care of which is nothing but making reusable components which further ensures the scalability and flexibility of the program or the code for a long time.
- Generics, thus here comes into the picture as it provides a user to flexibly write the code of any particular data type (or return type) and that the time of calling that user could pass on the data type or the return type specifically.
- Generics provides a way to make the components work with any of the data types (or return types) at the time of calling it for a certain number of parameters (or arguments).
- In generics, we pass a parameter called type parameter which is put in between the lesser sign (<) and the greater sign (>), for example, it should be like <type_parameter_name>.
Syntax for writing Generics:
Following syntax we may use to add generics into our pre-written piece of code (this is the syntax of using Generics in functions):
function function_name <type_parameter>
(parameter_name : data_type_parameter)
: return_type_parameter {
// Rest code......
}
Advantages of using Generics in TypeScript:
Following are the list of advantages that generics provide in TypeScript:
- By using generics we may safely store a single type of object without storing the other types too.
- By using generics we need not implement the typecasting of any variable or function at the time of calling.
- Generics are usually checked at the compile time so no issue exists in runtime.
Now after understanding all of the above-mentioned details which are associated with Generics, let us move forward and see some of the following code examples for a better understanding of Generics-
Example 1: In this example, we will simply see how we may try to create a generic function with generic parameters inside it and further how we may call that generic function with generic parameters.
JavaScript
function displayData <type_parameter>
(parameter :type_parameter) : type_parameter{
return parameter;
}
let result1 = displayData <string> ("GeeksforGeeks");
let result2 = displayData <string> ("Hello World !!");
let result3 = displayData <number> (1234567890);
console.log(result1);
console.log(result2);
console.log(result3);
Output:
GeeksforGeeks
Hello World !!
1234567890
Example 2: In this example, we may try to create a generic function with a generic return type of array along with the generic parameters (that too of generic array data type) passed in it and further how we may call that generic function which will return the array as the result.
JavaScript
let displayResult = <type_parameter>
(data_item : type_parameter[]) : type_parameter[] => {
return new Array <type_parameter>().concat(data_item);
}
let numbersArray = displayResult<number>
([50 , 60 , 80 , 90]);
let stringArray = displayResult<string>
(["Hello World", "GeeksforGeeks"]);
console.log(numbersArray);
console.log(stringArray);
numbersArray.push(100);
stringArray.push("Apple");
console.log(numbersArray);
console.log(stringArray);
Output:
[ 50, 60, 80, 90 ]
[ 'Hello World', 'GeeksforGeeks' ]
[ 50, 60, 80, 90, 100 ]
[ 'Hello World', 'GeeksforGeeks', 'Apple' ]
Example 3: In this example, we will be creating some multi-generic-type variables and will further see how we may call them inside our function which we are making for the execution.
JavaScript
let displayResult = <type_1, type_2>
(id : type_1, name : type_2) => {
return id + " - " + name;
}
let data_1 = displayResult<number,
string>(2000, "GeeksforGeeks");
let data_2 = displayResult<number,
string>(2001, "Hello World !!");
console.log(data_1);
console.log(data_2);
Output:
2000 - GeeksforGeeks
2001 - Hello World !!
Reference: https://www.typescriptlang.org/docs/handbook/2/generics.html
Similar Reads
What are TypeScript Interfaces?
TypeScript interfaces define the structure of objects by specifying property types and method signatures, ensuring consistent shapes and enhancing code clarity.Allow for optional and read-only properties for flexibility and immutability.Enable interface inheritance to create reusable and extendable
4 min read
What are Hybrid Types in TypeScript?
Hybrid types are used by TypeScript to refer to types that combine different things such as objects, functions, arrays etc. In this article, we will learn more about Hybrid Types in TypeScript.What are Hybrid Types in TypeScript?In TypeScript, using interfaces or type aliases we can define hybrid ty
2 min read
TypeScript Generic Classes
Generics in TypeScript allow us to create reusable and type-safe components. Generic classes help in defining a blueprint that can work with different data types without sacrificing type safety. They enable better code reusability and flexibility by allowing us to define type parameters that will be
5 min read
What is Type Erasure in TypeScript?
TypeScript is a very mighty superset of JavaScript, which adds static typing to the language and allows developers to catch errors early on as well as write more maintainable code. This being said a TypeScript type system erases type information at compile time (or during the compilation), a phenome
4 min read
What is Recursive Generic in TypeScript ?
In TypeScript, a recursive generic is a type that refers to itself within its definition, enabling the creation of data structures or types containing references to the same type within their structure. This capability proves invaluable when dealing with nested or hierarchical data structures like t
4 min read
What are the Modules in Typescript ?
Modules in TypeScript allow you to organize code into reusable, manageable, and logical units by encapsulating functionalities into separate files.They help avoid global namespace pollution by providing scoped declarations.Modules can be imported and exported, enabling code reuse and better maintain
4 min read
Typescript Generic Type Array
A generic type array is an array that is defined using the generic type in TypeScript. A generic type can be defined between the angled brackets(<>). Syntax:// Syntax for generic type arraylet myArray: Array<Type>;Example 1: Creating a simple generic type array of number type in Typescri
1 min read
What are âimplementsâ clauses in TypeScript ?
In Typescript an implements clause can be used to verify that a class conforms to a specific interface. If a class fails to implement an interface correctly, an error will be generated. Classes can implement a single interface or multiple interfaces at once. Example 1: An interface A is created with
2 min read
What are intersection types in Typescript ?
In Typescript, Although intersection and union types are similar, they are employed in completely different ways. An intersection type is a type that merges several kinds into one. This allows you to combine many types to create a single type with all of the properties that you require. An object of
3 min read
What are Abstract Classes in TypeScript?
An abstract class in TypeScript serves as a blueprint for other classes and cannot be instantiated directly. It may include abstract methods without implementation, which must be defined in any subclass.Additionally, it can contain concrete methods with implementations, properties, and other members
4 min read