DEV Community

Cover image for How to define advance types in Typescript
Bayu Setiawan
Bayu Setiawan

Posted on

How to define advance types in Typescript

Let's explore some of the advanced types that TypeScript offers and how they can be applied effectively:

  • Aliases
type Student = {
  readonly id: number;
  name: string;
  retire: (date: Date) => void;
};

let student: Student = {
  id: 1,
  name: 'bayu',
  retire: (date: Date) => {
    console.log(date);
  },
};

Enter fullscreen mode Exit fullscreen mode
  • Intersection
type Draggable = {
  drag: () => void;
};
type Resizeable = {
  resize: () => void;
};
type UIWidget = Draggable & Resizeable;

let textBox: UIWidget = {
  drag: () => {},
  resize: () => {},
};

Enter fullscreen mode Exit fullscreen mode
  • Literal
type Quantity = 50 | 100;
type Metric = 'cm' | 'mm';

let quantity: Quantity = 50;
let metric: Metric = 'cm';

Enter fullscreen mode Exit fullscreen mode
  • Never
function processEvent(): never {
  while (true) {
    // read a message from a queqe
  }
}
processEvent();
console.log('Hello World');

// clg never executed

Enter fullscreen mode Exit fullscreen mode
  • Nullable
function great(name: string | null | undefined) {
  if (name) console.log(name.toUpperCase());
  else console.log('parameter is nullable');
}

great(undefined);

Enter fullscreen mode Exit fullscreen mode
  • Nullish Coaelscing
let speed: number | null = null;
let ride = {
  // speed: speed !== null ? speed : 30
  speed: speed ?? 30,
};

Enter fullscreen mode Exit fullscreen mode
  • Optional Changing
type Customer = {
  birthday?: Date;
};

function getCostumer(id: number): Customer | null | undefined {
  return id === 0 ? null : { birthday: new Date() };
}

let customer = getCostumer(1);
// optional property access operator
console.log(customer?.birthday?.getFullYear());

// optional element access operator ex: array customer
// customer?.[0]

// optional call
let log: any = null;
log?.('a');

Enter fullscreen mode Exit fullscreen mode
  • Union
function convertion(weight: number | string) {
  if (typeof weight === 'number') return weight * 2;
  else return parseInt(weight) * 2;
}

convertion(10);
convertion('10');

Enter fullscreen mode Exit fullscreen mode
  • Unknown
function render2(document: unknown) {
  // Narrowing
  if (typeof document === 'string') {
    document.toUpperCase();
  }
  //   document.fly()
  //   document.whatEverYouWant()
}

Enter fullscreen mode Exit fullscreen mode

Advanced types in TypeScript equip you with powerful tools to handle complex scenarios, create reusable patterns, and ensure type safety in your projects. By employing union types, intersection types, conditional types, mapped types, type guards, template literal types, and even recursive types, you can elevate your code to new levels of expressiveness and maintainability.
This blog post has introduced you to the significance of advanced types, how they solve common development challenges, and how to apply them in various scenarios. Armed with this knowledge, you're ready to tackle intricate type relationships and create more resilient and adaptable TypeScript applications.
Hope this helps!

Top comments (0)