DEV Community

Cover image for Ts Interface vs Types
Amany khaled
Amany khaled

Posted on

Ts Interface vs Types

Difference between Interface and Types in Typescript.

In TypeScript, both interfaces and types are used to define the shape of an object or a function, but they have some differences in their syntax and usage.

1. Syntax:

Interfaces are declared using the interface keyword, followed by the name of the interface and its properties.
Types are declared using the type keyword, followed by the name of the type and its properties.

Here is an example of an interface and a type that define the same shape:

interface Person {
  name: string;
  age: number;
}

type Person = {
  name: string;
  age: number;
};

Enter fullscreen mode Exit fullscreen mode

2. Usage:

An interface is a contract that defines the shape of an object. It specifies the names and types of properties and methods that an object must have in order to be considered a valid instance of that interface.

A type alias, on the other hand, is a way to give a name to a type so that it can be used in multiple places in your code. It's like a shortcut for a longer, more complex type.

Here is an example of using an interface to define a function parameter:

interface Greeting {
  message: string;
}

function greet(person: Greeting) {
  console.log(`Hello, ${person.message}!`);
}

Enter fullscreen mode Exit fullscreen mode

3. Summary

In summary, both interfaces and types are used to define the shape of objects or functions, but interfaces are typically used for defining contracts while types are often used to define aliases or more complex types. Choosing which one to use depends on the specific use case and personal preference.

Top comments (0)