Generic Types

Generic Types

Generic types

Definition: “A generic type is a generic class or interface that is parameterized over types.”

or A generic type is a generic class or interface that is parameterized over types.

Generics (sometimes referred to as polymorphic types) is a way of abstracting a type away. Imagine writing the following identity function which returns whatever value was passed.

function identity(value) {
  return value;
}        

We would have a lot of trouble trying to write specific types for this function since it could be anything.

function identity(value: string): string {
  return value;
}        

Syntax of generics

There are a number of different places where generic types appear in syntax.

Functions with generics

Functions can create generics by adding the type parameter list <T> before the function parameter list.

You can use generics in the same places you’d add any other type in a function (parameter or return types).

function method<T>(param: T): T 
  // ...
}

function<T>(param: T): T {
  // ...
}
{        

Function types with generics

Function types can create generics in the same way as normal functions, by adding the type parameter list <T> before the function type parameter list. You can use generics in the same places you’d add any other type in a function type (parameter or return types).

Generics act like variables

Generic types work a lot like variables or function parameters except that they are used for types. You can use them whenever they are in scope.

function constant<T>(value: T): () => T 
{
  return function(): T {
    return value;
  };
}
        

It will be the same as the normal OOPS concept that will be available to us and we need to just use the ELEMENT <T>. To create a generic function or a class. A generic class has a similar shape to a generic interface. Generic classes have a generic type parameter list in angle brackets (<>) following the name of the class.

Here is an example of the whole generic usage that I have found on the internet

class BeeKeeper 
  hasMask: boolean = true;
}
 
class ZooKeeper {
  nametag: string = "Mikle";
}
 
class Animal {
  numLegs: number = 4;
}
 
class Bee extends Animal {
  keeper: BeeKeeper = new BeeKeeper();
}
 
class Lion extends Animal {
  keeper: ZooKeeper = new ZooKeeper();
}
 
function createInstance<A extends Animal>(c: new () => A): A {
  return new c();
}
 
createInstance(Lion).keeper.nametag;
createInstance(Bee).keeper.hasMask;        

References :


To view or add a comment, sign in

More articles by Arun Kumar Borru

  • TIME SERIES PREDICTION

    What is Arima? Autoregressive Integrated Moving Average (ARIMA) ARIMA is an acronym that stands for AutoRegressive…

  • K-Means Clustering Algorithm

    What is clustering? Clustering is the process of grouping together objects so that those in the same grouping (cluster)…

Explore content categories