Type vs Interface in TypeScript

Tram Ho

When working with Typescript, we often get “Confused” about using Type and interface. In this article I will analyze a few differences between Type and Interface.

Typescript advanced javascript, of course, but in addition to existing features of javascript, typescript provides us with a lot more other features, typically Static Type.

Basically typescript has 3 main types of types

  • Any type
  • Built in type
  • User defined type

Interface and Type are of the third type – User defined type.

1. Declaration

Type

Interface

2.Interface can merge and Type cannot

In the same file we declare the following

Everything is fine, and with Type

Here we will get the error: ” Duplicate identifier ‘Shape .”

3.Type can be used with “Computed Properties” and interface is not

Type

Interface

We will get the error A computed property name in an interface must refer to an expression whose type is a literal type or a ‘unique symbol’ type.

4.Tuples Type

5.Type has Unions type and interface is not

Type

In addition to defining types, Typescript also provides us with Utility Types that are very useful when working with Legacy code.

Summary

So when to use Type and when to use Interface, this is not personally distinguishable 😉 ). According to my work experience, use Inferface when:

-You write library – and provide public Api for others to use

Use type when:

You want something clearer than the interface

Share the news now

Source : Viblo