Difference Between Type and Interface in TypeScript

In TypeScript, an interface is a way to define the structure of an object. It’s a contract that defines the properties and their types that an object must have. Interfaces can also be used to define function signatures.
On the other hand, a type is a way to define a new type by combining one or more existing types. Types can be used to create aliases for existing types, as well as define unions, intersections, and other complex types. In short, interfaces are used to define object shapes and function signatures, while types are used to define new types by combining existing ones.

Example of Creating an Interface:


interface Person {
  firstName: string;
  lastName: string;
  age: number;
  sayHello: () => void;
}

const john: Person = {
  firstName: 'John',
  lastName: 'Doe',
  age: 30,
  sayHello() {
    console.log(`Hello, my name is ${this.firstName} ${this.lastName}`);
  }
};

john.sayHello(); // Output: "Hello, my name is John Doe"


In this example, we define an interface called Person that specifies the shape of an object that must have a firstName property of type string, a lastName property of type string, an age property of type number, and a sayHello method that takes no arguments and returns nothing. Then, we create an object john that conforms to the Person interface and use its sayHello method to log a message to the console.

Example of Creating a Type:


type Point = {
  x: number;
  y: number;
};

type Circle = Point & {
  radius: number;
};

type Square = Point & {
  sideLength: number;
};

function getArea(shape: Circle | Square): number {
  if ('radius' in shape) {
    return Math.PI * shape.radius ** 2;
  } else {
    return shape.sideLength ** 2;
  }
}

const circle: Circle = { x: 0, y: 0, radius: 10 };
const square: Square = { x: 0, y: 0, sideLength: 5 };

console.log(getArea(circle)); // Output: 314.1592653589793
console.log(getArea(square)); // Output: 25

In this example, we define three types: Point, Circle, and Square. The Point type is a simple object with x and y properties of type number. The Circle and Square types are defined as intersections of the Point type and an object with additional properties specific to each shape. We also define a function called getArea that takes a parameter of type Circle | Square and returns a number. Depending on whether the input shape is a circle or a square, the function calculates and returns the area of the shape.
Finally, we create objects of type Circle and Square and use them as arguments to the getArea function.

Conclusion

In conclusion, we have seen the differences and we have seen that interfaces are used to define object shapes and function signatures, while types are used to define new types by combining existing ones.

Happy Learning…