DEV Community

Cover image for How to use in Typescript: type or interface?
Luiz Calaça
Luiz Calaça

Posted on

How to use in Typescript: type or interface?

Hi, Devs!

There are two main types for declaring the shape of a
object: interfaces and types. Let's think about type and interface implemented on Typescript language and its goals.

They are very similar and for most cases work the same way.
Both can be extended:

type Database = { connection: string; };
type UserRepo = Database & { user: User; };
Enter fullscreen mode Exit fullscreen mode
interface Database { connection: string; }
interface UserRepo extends Database{ user: User; } 
Enter fullscreen mode Exit fullscreen mode

We can extends an interface with two ways:

1 - Duplicating the interface:

interface Person {
  name: string;
}

interface Person {
  description: string;
}
Enter fullscreen mode Exit fullscreen mode

2 - Using the reserved word: extends

interface Entreprise{
  description: string;
}

interface Person extends Enterprise{
  name: string;
}
Enter fullscreen mode Exit fullscreen mode

A type alias can extend an Interface, and vice versa.

type Database = { connection: string; };

interface UserRepo extends Database {}
Enter fullscreen mode Exit fullscreen mode
interface Database {}

type UserRepo = Database & { name: string; };

Enter fullscreen mode Exit fullscreen mode

Discussion

1 - I prefer use only interface, because it is show us clearly what we are gonna do in oriented object programming;
2 - For programers of others languages would be more readable if we use interface instead of type;
3 - For a good practice in a clean code and a better software architecture I'd use only one interface instead of duplicate it. There're things that not always is an advantage and can complicate our clean code.

And what you think about this context?

Contacts
Email: luizcalaca@gmail.com
Instagram: https://www.instagram.com/luizcalaca
Linkedin: https://www.linkedin.com/in/luizcalaca/
Twitter: https://twitter.com/luizcalaca

Top comments (7)

Collapse
 
sinh117801 profile image
Sinh

Thanks for sharing. For me personally, I prefer using Type for object or function params, and interface for class with property or methods

Collapse
 
luizcalaca profile image
Luiz Calaça

Hello, Sinh. Thanks for your contribution, excellent point!

Collapse
 
sinh117801 profile image
Sinh

For me this way is much cleaner and more readable.

Thread Thread
 
luizcalaca profile image
Luiz Calaça

I also agree.

Collapse
 
curiousdev profile image
CuriousDev

Thanks for this and can you please add more details about the difference of interface and type?

Collapse
 
andrewbaisden profile image
Andrew Baisden

Good topic.

Collapse
 
alexandrecalaca profile image
Alexandre Calaça

Outstanding!