DEV Community

What is your way declare types for objects in TypeScript?

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;
}
Enter fullscreen mode Exit fullscreen mode

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" };
Enter fullscreen mode Exit fullscreen mode

So, here is my questions for you folks:

  1. Are you using interfaces over types?
  2. Why do you prefer interfaces?
  3. Do you think interfaces are still a relevant feature in TypeScript?

I would be glad to receive your thoughts about interfaces)))

Top comments (6)

Collapse
 
gad profile image
Vladislav

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.

Collapse
 
svitlana_toporkova_ee618a profile image
Svitlana

For me sing types is rather question of general approach for data typing in app, it's convenient when everything using types.

Collapse
 
cookiemonsterdev profile image
Mykhailo Toporkov πŸ‡ΊπŸ‡¦

Same for me, I like to have the same typing style across whole app)))

Collapse
 
benderrodriguez profile image
Bender rodriguez

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.

Collapse
 
hasanabi profile image
Hasan Abi

Not sure if interfaces are still relevant to use considering types features, on the other side dropping support also not an option.

Collapse
 
taranka profile image
Sivak Ihor

ty for your article