Table of contents
1.
Introduction
2.
TypeScript Type
2.1.
Implementation
2.2.
Output
2.3.
Explanation
3.
Interface
3.1.
Implementation
3.2.
Output
3.3.
Explanation
4.
TypeScript Type vs. Interface
5.
Differences between Types and Interfaces
5.1.
Primitive Types
5.2.
Union Types
5.3.
Declaration Merging
5.4.
Extends vs. Intersection
5.5.
Handling Conflicts when Extending
6.
Frequently Asked Questions
6.1.
Should we use the Interface or type in TypeScript?
6.2.
What is the main advantage of types in TypeScript?
6.3.
What is the main difference between type and Interface?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

TypeScript Type vs. Interface

Author Kanak Rana
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

TypeScript is becoming one of the most used languages for development. Has gained popularity in the web development industry due to its ability to introduce static typing to JavaScript, improving code quality and maintainability. In TypeScript, an interface defines the structure of a class, specifying its properties, methods, and events. 

TypeScript Type vs. Interface

It helps with type-checking and ensures that classes follow a particular structure.

On the other hand, a type in TypeScript specifies the data type of variables. It determines the kind of value a variable can hold. Interfaces define class structures, while types define variable data types in TypeScript.

This article will look at the TypeScript Type vs. Interface and when to utilize each.

TypeScript Type

In TypeScript, each data has a specific type that defines its nature, such as string, boolean, or number. TypeScript also offers advanced types, and one helpful feature is called type aliases.

Type aliases enable us to create alternative names for existing types without creating new types from scratch. Using the "type" keyword, we can create a new name (alias) for an existing type to make the code more readable and maintainable.

Implementation

// Type alias for a string or number
type ID = string | number;

// Type alias for an object representing a person
type Person = {
  name: string;
  age: number;
  gender: 'male' | 'female' | 'other';
};

// Function using type aliases
function printUserInfo(id: ID, person: Person) {
  console.log(`ID: ${id}`);
  console.log(`Name: ${person.name}`);
  console.log(`Age: ${person.age}`);
  console.log(`Gender: ${person.gender}`);
}

// Usage
const userId: ID = 12345;
const user: Person = {
  name: 'Rohan',
  age: 30,
  gender: 'male',
};
printUserInfo(userId, user);
You can also try this code with Online Javascript Compiler
Run Code

Output

ID: 12345
Name: Rohan
Age: 30
Gender: male

Explanation

The code defines type aliases for ID and Person and includes a function printUserInfo() that takes an ID and a Person object as parameters.

Interface

An interface comprises the properties, methods, and events that it defines. It contains only the declarations of these members, while their actual implementation is the responsibility of the derived class. TypeScript compiler utilizes interfaces for type-checking and helps to establish a consistent structure that derived classes must follow. Interfaces are created using the interface keyword.

Implementation

//Interface definition
interface Rectangle {
  width: number;
  height: number;
  calculateArea(): number;
}

// Derived class implementing the Rectangle interface
class Square implements Rectangle {
  width: number;
  height: number;

  constructor(side: number) {
    this.width = side;
    this.height = side;
  }

  calculateArea(): number {
    return this.width * this.height;
  }
}

// Usage
const square = new Square(5);
console.log("Square area:", square.calculateArea()); 
You can also try this code with Online Javascript Compiler
Run Code

Output

Square area: 25

Explanation

Code defines a "Rectangle" blueprint with "width," "height," and "calculate area ()" methods. It's used to create a "Square" with equal "width" and "height." A square of side length 5 has an area of 25 (5 * 5).

TypeScript Type vs. Interface

Feature TypeScript Type  Interface
Purpose Defines data types of variables Defines a structure of objects and classes
Declaration Keyword type interface
Syntax type Name = DataType interface Name { ... }
Usage Variables, unions, complex types Objects, classes, related entities
Declaration Merging It can be easily merged Automatically merged
Extensibility Cannot extend other types Can extend other interfaces
Implementability Classes cannot implement it Can be implemented by classes
Compatibility Less strict compatibility check More strict compatibility check
Type Inference Works well with type inference Works well with type inference
Utility functions Cannot define utility functions Cannot define utility functions directly

Differences between Types and Interfaces

Primitive Types

  • Types can represent primitive data types like string, number, boolean, etc
  • Interfaces cannot directly represent primitive types but can be used to describe complex structures containing primitive types

Union Types

  • Both Types and Interfaces can represent union types, combining multiple data types
  • Union types allow variables to hold different types of values

Declaration Merging

  • Types support declaration merging, meaning multiple type declarations with the same name are combined
  • Interfaces automatically merge declarations with the same name, extending the original interface definition

Extends vs. Intersection

  • Types use "extends" to extend or inherit from other types
  • Interfaces use intersection (`&`) to combine multiple interfaces

Handling Conflicts when Extending

  • When extending types with conflicting property names, the latter type definition overwrites the former
  • When extending interfaces with conflicting property names, both property definitions are combined

Frequently Asked Questions

Should we use the Interface or type in TypeScript?

Use the Interface when defining contracts for objects, classes, or related entities. Use type for unions, complex types, or utility functions. Consider readability and consistency when choosing between them.

What is the main advantage of types in TypeScript?

The main advantage of types in TypeScript is that they allow us to explicitly define and enforce the data types of variables, ensuring type safety and catching potential errors early during development. This leads to more reliable and maintainable code.

What is the main difference between type and Interface?

Type is used to define data shapes, including primitive types and unions. The interface defines contracts for objects and classes with specific structures and behavior, promoting code organization and consistency.

Conclusion

In this article, we discussed TypeScript Type vs Interface. We discussed both the type and Interface in detail. In the end, we concluded by discussing some different points in applications and some frequently asked questions.

Now that you know TypeScript Type vs. Interface, you can refer to similar articles.


You may refer to our Guided Path on Code Studios for enhancing your skill set on DSA, Competitive Programming, System Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy Learning!

Live masterclass