Advertisement
← Back to Examples

TypeScript Examples

Generics Example

Create reusable generic functions

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

const str = identity<string>("Hello");
const num = identity<number>(42);

Utility Types

Use built-in TypeScript utility types

interface User {
  id: number;
  name: string;
  age?: number;
}

type UserPreview = Pick<User, "id" | "name">;
type UserOptional = Partial<User>;
type UserRequired = Required<User>;

Decorators

Add behavior to classes or properties

function Log(target: any, propertyKey: string) {
  let value = target[propertyKey];

  const getter = () => {
    console.log("Get:", propertyKey);
    return value;
  }

  const setter = (newVal: any) => {
    console.log("Set:", propertyKey, newVal);
    value = newVal;
  }

  Object.defineProperty(target, propertyKey, {
    get: getter,
    set: setter,
    enumerable: true,
    configurable: true
  });
}

class Person {
  @Log
  name: string;

  constructor(name: string) {
    this.name = name;
  }
}

const p = new Person("Alice");
p.name = "Bob";
Advertisement