Types & Interfaces
TypeScript adds static type definitions to JavaScript, catching structural mismatches during development before code reaches runtime. Primitives include string, number, boolean, null, undefined, and symbol. You define complex object contracts using either type aliases or interface declarations.
While type aliases can represent primitive unions (type Status = 'pending' | 'success'), tuple types, and mapped types, interface declarations excel at defining object structures and support declaration merging across modules. Best practice is to use interface for public library APIs and extensible domain models, and type for unions, primitives, and complex type transformations.
Exercise
Create a UserRole union type and a UserProfile interface with optional and readonly properties.
Check your understanding
What is declaration merging in TypeScript interfaces?Show answerHide answer
Answer
If multiple interface declarations share the same name in the same scope, TypeScript automatically merges their property definitions into a single interface.When should you use a type alias instead of an interface?Show answerHide answer
Answer
Use a type alias when defining union types, tuple types, primitive aliases, or mapped types.