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.
interfaceis intended for describing the shape of an object, supports declarative extension (inheritance) viaextends, and can be merged in multiple declarations (declaration merging).typeallows 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 throughextends:
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:
interfaceis better suited for describing objects and classes, supports declarative extension and merging.typeis 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.