Objects, Interfaces, and Type Aliases
In TypeScript, you can describe what an object looks like and how your data is built. You do this using interfaces and type aliases. These help you set clear rules for your code, so it is easier to read and fix later. In this section, we will learn how to write object types, use interfaces to describe the shape of objects, make type aliases for more complex types, and understand the difference between interfaces and type aliases. By the end of this section, you will understand how to work with objects, interfaces, and type aliases in TypeScript.
Object Type Annotation
Section titled “Object Type Annotation”let user: { name: string; age: number } = { name: "Sahil", age: 22,};This works fine, but it is hard to reuse this same type again somewhere else in your code.
Interface
Section titled “Interface”interface User { name: string; age: number;}Use an interface when you want to clearly describe the shape of an object.
Type Alias
Section titled “Type Alias”type User = { name: string; age: number;};A type alias can also be used for unions, tuples, and other complex type combinations, not just plain objects.
Interface vs Type
Section titled “Interface vs Type”- Good for object-oriented style design
- Supports declaration merging (you can reopen it later and add more to it)
- Commonly used for class contracts
- Works for objects, unions, intersections, and tuples
- Better when you want to build advanced type logic
- Cannot be reopened once it is declared
Interface Reopening
Section titled “Interface Reopening”interface User { name: string;}interface User { age: number;}Now User has both name and age properties. This is called declaration merging - TypeScript automatically joins both interface blocks into one.
Intersection Types
Section titled “Intersection Types”type A = { name: string };type B = { age: number };type Person = A & B;Person must have all the properties from both A and B. The & symbol joins the two types together into one bigger type.
Interfaces with Methods
Section titled “Interfaces with Methods”interface Calculator { add(a: number, b: number): number;}Method signatures (the function rules written inside an interface) make it clear what a piece of code should do, without writing the actual logic.