Sobes.tech
Middle+

How does the keyword 'type' differ from 'interface' in TypeScript? Explain inheritance in types and interfaces.

sobes.tech AI

Answer from AI

In TypeScript, the keyword type is used to declare type aliases, while interface is used to describe object structures and contracts.

  • interface is intended for describing the shape of an object, supports declarative extension (inheritance) via extends, and can be merged in multiple declarations (declaration merging).
  • type allows creating aliases for any types (primitives, unions, intersections, tuples, etc.), but does not support declarative extension, although types can be combined using & (intersection) and | (union).

Inheritance:

  • In interface, inheritance is done through extends:
interface A { a: string }
interface B extends A { b: number }
  • In type, inheritance is implemented through type intersections:
type A = { a: string }
type B = A & { b: number }

Main differences:

  • interface is better suited for describing objects and classes, supports declarative extension and merging.
  • type is more versatile, allows describing complex types, but does not support declarative extension of interfaces.

The choice depends on the task: if you need to describe an object structure with the possibility of extension — use interface; if you need a complex composite type — use type.