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; };
interface Database { connection: string; }
interface UserRepo extends Database{ user: User; }
We can extends an interface with two ways:
1 - Duplicating the interface:
interface Person {
name: string;
}
interface Person {
description: string;
}
2 - Using the reserved word: extends
interface Entreprise{
description: string;
}
interface Person extends Enterprise{
name: string;
}
A type alias can extend an Interface, and vice versa.
type Database = { connection: string; };
interface UserRepo extends Database {}
interface Database {}
type UserRepo = Database & { name: string; };
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)
Thanks for sharing. For me personally, I prefer using Type for object or function params, and interface for class with property or methods
Hello, Sinh. Thanks for your contribution, excellent point!
For me this way is much cleaner and more readable.
I also agree.
Thanks for this and can you please add more details about the difference of interface and type?
Good topic.
Outstanding!