0
0
Typescriptprogramming~5 mins

Why advanced types are needed in Typescript

Choose your learning style9 modes available
Introduction

Advanced types help us describe complex data clearly. They make programs safer by catching mistakes early.

When you want to check that a function only accepts certain shapes of data.
When you need to combine different types of data into one variable safely.
When you want to make sure your program handles many possible data forms without errors.
When you want to create reusable and clear rules for data in your code.
When you want to avoid bugs by telling TypeScript exactly what kind of data to expect.
Syntax
Typescript
type MyType = string | number;
type User = { name: string; age: number };
type Response = User & { status: string };

Use | to say a value can be one of many types (union).

Use & to combine types together (intersection).

Examples
This shows a variable that can be a string or a number.
Typescript
type ID = string | number;
let userId: ID = 123;
userId = "abc";
This combines two types so emp must have both name and salary.
Typescript
type Person = { name: string };
type Employee = Person & { salary: number };
let emp: Employee = { name: "Anna", salary: 5000 };
This shows a union type used to handle success or error results safely.
Typescript
type Result = { success: true; data: string } | { success: false; error: string };
function handle(res: Result) {
  if (res.success) {
    console.log(res.data);
  } else {
    console.log(res.error);
  }
}
Sample Program

This program uses an advanced union type to represent different shapes. The area function calculates the area based on the shape kind. This helps avoid mistakes by making sure only valid shapes are used.

Typescript
type Shape = { kind: "circle"; radius: number } | { kind: "square"; size: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.size ** 2;
  }
}

const myCircle: Shape = { kind: "circle", radius: 3 };
const mySquare: Shape = { kind: "square", size: 4 };

console.log(area(myCircle));
console.log(area(mySquare));
OutputSuccess
Important Notes

Advanced types help TypeScript understand your data better.

They reduce bugs by checking data shapes before running the program.

Using them makes your code easier to read and maintain.

Summary

Advanced types let you describe complex data clearly.

They help catch errors early by checking data shapes.

Using them makes your code safer and easier to understand.