Generic

Function

// arrow function
const identity = <T>(arg: T): T => {
    return arg;
};

// traditional function
function identity<Type>(arg: Type): Type {
  return arg;
}

// Example usage:
const result1 = identity<number>(42); // Explicitly specifying the type
const result2 = identity("Hello"); // TypeScript infers the type
console.log(result1); // Output: 42
console.log(result2); // Output: Hello

Interface & Type

// interface
interface Pair<T, U> {
    first: T;
    second: U;
}

// Example usage:
let pair: Pair<number, string> = { first: 42, second: "Hello" };
console.log(pair); // Output: { first: 42, second: "Hello" }

// Type
type Test<K extends keyof any, V> = Record<K, V>;
const a:Test<string,string> = {
  "a": "123"
}

// Class
class Box<T> {
  content: T;
  constructor(content: T) {
      this.content = content;
  }

  getContent(): T {
      return this.content;
  }
}

// Example usage:
const numberBox = new Box<number>(42);
console.log(numberBox.getContent());

Last updated

Was this helpful?