class template in typescript in javascript

To create a class template in TypeScript, you can use the class template<T> which allows you to define a generic class that can take any type as a parameter. Here's an example:

index.ts
class MyClass<T> {
  private _value: T;

  constructor(value: T) {
    this._value = value;
  }

  getValue(): T {
    return this._value;
  }
}

// Creating a new instance of MyClass with a string type parameter
const myStringClass = new MyClass<string>('Hello World');

// Calling the getValue method to retrieve the string value
console.log(myStringClass.getValue()); // Output: Hello World

// Creating a new instance of MyClass with a number type parameter
const myNumberClass = new MyClass<number>(123);

// Calling the getValue method to retrieve the number value
console.log(myNumberClass.getValue()); // Output: 123
625 chars
24 lines

In the example above, we created a generic class MyClass which takes a type parameter T. The class has a private property _value of type T which is set through the constructor when a new instance of the class is created. We also have a method getValue which returns _value.

To instantiate the class, we provide a type parameter for T as a generic argument. In this example, we provided the string and number types as arguments when creating two different instances of MyClass.

This is just a simple example, but you can use class templates in TypeScript to create powerful and flexible classes that can work with a variety of different types.

gistlibby LogSnag