In JavaScript, you sometimes need classes that can work with different data types. JSDoc generics help achieve this flexibility [3].
Here's how it works:
Creating a Container Class:
```javascript
/**
* @template T - Use the `@template` tag to add a type parameter to the class.
* @class
*/
class Container {
/**
* @param {T} value - The constructor takes a value of type T.
*/
constructor(value) {
this.value = value;
}
/**
* @return {T} - The `getValue` method returns a value of type T.
*/
getValue() {
return this.value;
}
}
```
How it Works:
* The `@template` tag introduces a type parameter, `T`, to the `Container` class. Think of it as a placeholder for different data types [4].
* The constructor can accept a value of type `T`. This means you can create instances of `Container` with various data types while ensuring data type consistency.
* The `getValue()` method always returns a value of the same type, `T`, that you initially stored. This ensures that your data remains consistent.
Let's see how it's applied for various inputs like `boolean`,`string`, `array` , `object` and `number`:
```
// Example with a string input
const stringContainer = new Container("Hi, It is a sample code...");
console.log(stringContainer.getValue()); // Output: "Hi, It is a sample code..."
// Example with a number input
const numberContainer = new Container(49);
console.log(numberContainer.getValue()); // Output: 49
// Example with an array input
const arrayContainer = new Container([1, 2, 3]);
console.log(arrayContainer.getValue()); // Output: [1, 2, 3]
// Example with an object input
const objectContainer = new Container({ name: "John", age: 40 });
console.log(objectContainer.getValue()); // Output: { name: "John", age: 40 }
// Example with a boolean input
const booleanContainer = new Container(true);
console.log(booleanContainer.getValue()); // Output: true
```
In this example, `textContainer` works with a `string` data type, while `numberContainer` handles a `number`. Similarly, You can create instances tailored to specific data types, making your code adaptable and reusable [5].
JSDoc generics empower your JavaScript classes to handle different data types with ease, adding flexibility and efficiency to your projects.