TypeScript: Generic type definitions

Generic type definitions in TypeScript are useful in certain cases with function definitions. In some cases the function may accept any type of input and the output type should be defined based on the input type.

Lets make it more clear with an example

Generic type definitions usage in TypeScript – example

function insertAtBeginning<T>(array: T[], value: T) {
  const newArray = [value, ...array];
  return newArray;
}

const demoArray = [1, 2, 3];

const updatedArray = insertAtBeginning(demoArray, -1); // [-1, 1, 2, 3]
const stringArray = insertAtBeginning(['a', 'b', 'c'] , 'd')

In the above example we have defined a function insertAtBeginning<T>. It takes inputs an array and a value – which can of any type so we gave a generic type name T . So that the return output of the function will of the same type T.

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *