DEV Community

Maksim Nesterenko
Maksim Nesterenko

Posted on

Type vs Interface in typescript

Today I learned some funny differences between types and interfaces in typescript.

I used to think there was almost no practical difference between the type and interface and it all boils down to team preferences, but turned out these two behave quite differently when it comes to index signatures. The usage of interfaces can produce unexpected type incompatibilities (=TSC errors). Take a look at this example:

interface C {
    [x:string]: number
}
interface D {
    x: number
}
const d: D = { x: 1 };
const c: C = d; // error
// Type 'D' is not assignable to type 'C'.
//   Index signature is missing in type 'D'.
Enter fullscreen mode Exit fullscreen mode

But change the interface D to type D and it'll be alright.

You can read more about it here https://github.com/microsoft/TypeScript/issues/15300#issuecomment-371353444

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay