What is your way declare types for objects in TypeScript?

Mykhailo Toporkov πŸ‡ΊπŸ‡¦ - Sep 3 - - Dev Community

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

. . . . . . . . . . . . . . . . . . . .
Terabox Video Player