What is your way declare types for objects in TypeScript?
Mykhailo Toporkov 🇺🇦

Mykhailo Toporkov 🇺🇦 @cookiemonsterdev

About: Hi there! I'm a Full-Stack engineer who is always ready for new challenges. Also I hate russians!

Location:
Ukraine
Joined:
Nov 12, 2023

What is your way declare types for objects in TypeScript?

Publish Date: Sep 3 '24
25 6

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)))

Comments 6 total

  • Sivak Ihor
    Sivak IhorSep 3, 2024

    ty for your article

  • Hasan Abi
    Hasan AbiSep 4, 2024

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

  • Bender rodriguez
    Bender rodriguezSep 4, 2024

    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.

  • Svitlana
    SvitlanaSep 5, 2024

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

  • Vladislav
    VladislavSep 6, 2024

    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.

Add comment