Intro
TypeScript is a great "onbuild" for JavaScript that adds static types and helps us catch errors early during development, and even though, sometimes you need to break your brain to type some function it is still wonderful.
Essentially TS offers two ways to type objects: using the type
or interface
keyword. Initially, when I first started using TS, I relied solely on interfaces for objects, classes, React component props, etc. However, now I primarily use types and don't see much reason to use interfaces anymore...
Interface and type declarations:
interface Cat {
name: string;
color: string;
}
////////////////
type Cat = {
name: string;
color: string;
}
With type
, we can create type declarations that are identical to those made with interfaces, and even more. Types also allow for unions and intersections, which are incredibly useful features. As far as I remember, the only thing that cannot be replicated with types is declaration merging:
interface Cat {
name: string;
}
interface Cat {
color: string;
}
const pussinBoots: Cat = { name: "puss", color: "ginger" };
So, here is my questions for you folks:
- Are you using interfaces over types?
- Why do you prefer interfaces?
- Do you think interfaces are still a relevant feature in TypeScript?
I would be glad to receive your thoughts about interfaces)))
Top comments (6)
I prefer using interfaces exclusively with classes and avoid mixing them with types. To me, using types in conjunction with classes feels like bad practice.
For me sing types is rather question of general approach for data typing in app, it's convenient when everything using types.
Same for me, I like to have the same typing style across whole app)))
Flexibility with types makes it easier to manage complex structures, especially with unions and intersections. Interfaces have their place like when you extending some database model etc.
Not sure if interfaces are still relevant to use considering types features, on the other side dropping support also not an option.
ty for your article