Typescript generics are used to generate reusable code and in accordance with the type. The system applies, among other things, to functions, classes, interfaces and alias of types.
What is the typecript generics?
In almost all programming languages, there are tools that allow users to create code models which can be reused later or in other projects. The objective is not only to save time, but also to create a safe code that fits perfectly into new environments. Different components, functions and full data structures can be written and replicated in this way, Without losing their type of safety. In TypeScript, these tasks are performed using generics. The types can thus be transmitted as parameters to other types, functions or data structures.
Managed NextCloud of Ionos Cloud
Work as a team in your own cloud
- Data security
- Integrated collaboration tools
- Accommodation in European data centers
Syntax and operation using a simple example
THE Generic variables constitute the basis of the work with the typescript generics. These operate as benchmarks and indicate the type of data that must be declared later. In the code, they are identified with any capital letter. When creating the code, these variables are placed in sharp parentheses. They are assigned the real type name, so that the Typecript function, the desired type interface or class is replaced the generic character. This fictitious parameter, this landmark, is also called » type parameter ». It is possible to place several of these type parameters inside a parenthesis. The Syntax of Typescript Generics is represented in this simple example:
function ExempleDeFonction(parameter1: T): void {
console.log(`Le type de données du paramètre ${parameter1} est : ${typeof parameter1}`)
}
Typescript
Here we use the name of the function (« function of function ») to define the generic variable « T ». In the following code, we declare this variable as string (character string):
ExempleDeFonction("Ici se trouve un string.");
Typescript
If we now attribute the parameter value string To the function, we obtain the following result:
Le type de données du paramètre Ici se trouve un string. est : string
Typescript
Typescript generics with two variables
Typescript generics operate very similarly when two or more generic variables are used as a fictitious parameter. In the following example, we deposit the variables « T2 » and « U » as types for the parameters « parameter1 » and « parameter2 ». They are separated by a comma:
function ExempleDeFonction(parameter1: T, parameter2: U): string {
return JSON.stringify({parameter1, parameter2});
}
Typescript
We now provide data types and values to the two generic replacement characters; namely, in this case, the types of data number And string as well as the values »11″ and « players ». Here is the corresponding code:
const str = ExempleDeFonction(11, "Joueurs");
console.log(str);
Typescript
Examples of reproducible classes
If you want to use types script generics to create Reproducible classesit is possible. In the following example, we use generics to display a number. Here is the corresponding code:
class ValeurNumérique {
private _value: T | undefined;
constructor(private name: string) {}
public setValue(value: T) {
this._value = value;
}
public getValue(): T | undefined {
return this._value;
}
public toString(): string {
return `${this.name}: ${this._value}`;
}
}
let value = new ValeurNumérique('monNombre');
value.setValue(11);
console.log(value.toString());
Typescript
You get the following result:
The principle also works with other types of data and several generic variables, as shown in the example below:
class ClasseExemple {
prénom: T;
nom: U;
constructor(prénom: T, nom: U) {
this.prénom = prénom;
this.nom = nom;
}
}
Typescript
We now attribute to each of the variables the type of String data and the values provided:
const person1 = new ClasseExemple("Julie", "Rault");
console.log(`${person1.prénom} ${person1.nom}`)
Typescript
This time, the result is:
If you want to combine different types of data, proceed as follows:
class ClasseExemple {
nombre: T;
mot: U;
constructor(nombre: T, mot: U) {
this.nombre = nombre;
this.mot = mot;
}
}
Typescript
Now data types number And string As well as their values are attributed to the replacement characters:
const combinaison = new ClasseExemple(11, "Joueurs");
console.log(`${combinaison.nombre} ${ combinaison.mot}`);
Typescript
The result is as follows:
Use with interfaces
The use of types Script generics is possible and even recommended for interfaces. The procedure is similar to that of the declaration of a class:
interface Interface {
valeur: T;
}
Typescript
We now implement the interface in the “classexample” class. We attribute to the « T » variable the type of data string ::
class ClasseExemple implements Interface {
valeur: string = "Ceci est un exemple avec une interface";
}
const valeur = new ClasseExemple();
console.log(valeur.valeur)
Typescript
The result is as follows:
Ceci est un exemple avec une interface
Typescript
Create generic paintings
It is also possible to call on types Script Generics for typescript arroys. Here is a simple example of code in which the function is used reverse To reverse the order of numbers of a painting:
function reverse(array: T[]): T[] {
return array.reverse();
}
let nombres: number[] = [10, 7, 6, 13, 9];
let nouvelOrdre: number[] = reverse(nombres);
console.log(nouvelOrdre);
Typescript
We then obtain the following result:
[9, 13, 6, 7, 10]
Typescript
Typescript generics for conditional types
Finally, let's look at the use of conditional types with typescript generics. The result changes according to whether a condition is fulfilled or not. In the following example, this condition is the type of data string. Here is the corresponding code:
THE type A is therefore the « example » thong, while the type B is an object with the « name » property and the data type string. These two types are then recorded as « premiere » and « second -rings ». If we then check the two types, we note that « first -rings » receives the value True As a thong, while « second -cultural » remains False.
Advice
Deployment directly via GitHub: Deploy Now Ionos is an excellent choice for websites and applications thanks to automatic framework detection, quick installation and optimal scalability. Choose the price best suited to your project!

