Writing out complex object types inline repeatedly is very messy and inefficient.
TypeScript solves this by allowing you to name your types using Aliases and Interfaces.
Both accomplish very similar goals but have slightly different syntax and behaviors.
They are the absolute backbone of clean and reusable TypeScript programming.
A Type Alias allows you to create a custom name for any given type.
You define it using the type keyword, followed by an equals sign.
You can use Aliases for primitives, objects, unions, and complex structures.
type CarYear = number; type CarMake = string;type Car = { make: CarMake; year: CarYear; };
const myCar: Car = { make: "Ford", year: 2021 };
console.log("My Car:", myCar.make, myCar.year);
Interfaces are very similar to Type Aliases, but they only apply to object shapes.
You define them using the interface keyword, without using an equals sign.
They are often preferred in Object-Oriented Programming and when writing external libraries.
interface Rectangle {
width: number;
height: number;
}
const rect: Rectangle = {
width: 20,
height: 10
};
console.log("Rectangle Dimensions:", rect.width, "x", rect.height);
The main difference is that Interfaces can be merged or extended easily via declaration merging.
Type Aliases cannot be re-opened to add new properties later on.
Choosing between them is often a matter of team preference, but Interfaces scale better.
interface Animal { name: string; }
interface Dog extends Animal { breed: string; }
const myDog: Dog = { name: "Rex", breed: "Husky" };
console.log("My Dog:", myDog.name, "-", myDog.breed);
Which keyword allows you to extend an Interface with new properties?
Interfaces and Types help keep your code extremely DRY (Don't Repeat Yourself).
Use Interfaces for objects and Classes, and Types for unions and primitives.
Next, we will explore the flexibility of Union Types!