Typescript: Type vs Interface

Typescript: Type vs Interface

Let’s talk about the difference between Type and Interface in Typescript,

In the latest versions of Typescript the differences between them are minimal, and Type now can be used over interface in almost all cases.

Both Interface and Type can be used to describe the properties of an object or a function signature. But the syntax differs

As it is clear from the sample above, for object declaration there are no difference between them except for syntax changes. Interface syntax is like Class declaration and Type is like object declaration.

Type and interface both can be used for function signature, see the example below

Starting Typescript 2.2, it’s now possible to have an interface that extends object-like type

Now it is possible that Interface can extend a Type

Now lets see what features does the Type has that Interface does not

  1. Primitive Alias using Type we can create an alias for some primitive value, for example alias for unique ID, and use it in other interfaces or types for more meaningful and understandable code.

if alias is not for a primitive value, but for an array, then we can use either type or interface

2. Tuples allow us to use this new data type that includes two sets of values of different data types.

Tuple: is an array of a unchanged size and act as a constant in the world of arrays

3. Intersection allows us to combine multiple types into a single one type. To create an intersection type, we have to use the & keyword:

4. Union allow us to create a new type that can have a value of one or a few more types. To create a union type, we have to use the | keyword.

5. Auto Merge works only with Interfaces. if type get declared multiple times then typescript compiler throws an error.

Typescript merges the two declaration for Interface

Conclusion

In this article, We went through the similarities between Type and Interface and listed Type features that differs from Interface.

Interface is a great candidate for defining public API or third-party type definition.

Thanks for reading — I hope you found this piece useful. Happy coding!