typescript pass type as parameter code example

Example 1: typescript parameter function type

class Foo {
    save(callback: (n: number) => any) : void {
        callback(42);
    }
}
var foo = new Foo();

var strCallback = (result: string) : void => {
    alert(result);
}
var numCallback = (result: number) : void => {
    alert(result.toString());
}

foo.save(strCallback); // not OK
foo.save(numCallback); // OK

Example 2: typescript generic class

class Person<T, U, C> {
  name: T
  age: U
  hobby: C[]

  constructor(name: T, age: U, hobby: C[]) {
    this.name = name
    this.age = age
    this.hobby = hobby
  }
}

const output = new Person<string, number, string>('john doe', 23, ['swimming', 'traveling', 'badminton'])
console.log(output)

Example 3: typescript class type t

class GenericNumber<T> {
    zeroValue: T;
    add: (x: T, y: T) => T;
}

let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };

Example 4: typescript generic type

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

Example 5: typescript set argument type

// non typed function
function add(x, y) {
  return x + y;
}

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

// types can be found here: https://www.typescriptlang.org/docs/handbook/basic-types.html

Example 6: how to make a generic variable in javascript

var x = 1;
var y = 1;
if (x == y) {
  x = x + 1
}