generic type typescript function code example

Example 1: typescript generic function

function firstElement<Type>(arr: Type[]): Type {
  return arr[0];
}
// s is of type 'string'
const s = firstElement(["a", "b", "c"]);
// n is of type 'number'
const n = firstElement([1, 2, 3]);

Example 2: typescript generic type

function identity<T>(arg: T): T {
  return arg;
}Try

Example 3: typescript function

// Named function
function add(x: number, y: number): number {
  return x + y;
}

// Anonymous function
let myAdd = function (x: number, y: number): number {
  return x + y;
};

Example 4: simple function in typescript

// Named function

//function with type as number
function add(x: number, y: number): number {
  // return sum of numbers entered as params
  return x + y;
}

// Anonymous function

// variable to call and define function
let myAdd = function (x: number, y: number): number {
  // return sum of numbers entered as params
  return x + y;
};