Objects & Interfaces
Two ways to define an object's shape, and the subtle difference between them.
Types vs Interfaces
When you need to define the shape of an object in TypeScript, you have two choices: a type alias or an interface.
For 95% of everyday code, they do exactly the same thing. You define the keys, the value types, and whether any keys are optional (using ?).
The Declaration Merging trick
The primary functional difference between the two is a feature called **Declaration Merging**.
If you declare an interface named Window and then declare *another* interface named Window lower down in the file, TypeScript will merge their properties together. If you try to do this with a type alias, TypeScript will throw a 'Duplicate identifier' error.
Syntax comparison
Using an interface:
typescript
interface User {
id: number;
name?: string; // Optional property
}
Using a type alias (note the equals sign):
typescript
type User = {
id: number;
name?: string;
};
Try it
Toggle between type and interface to see how TypeScript handles you trying to declare the exact same name twice.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
interfaceandtypecan both describe object shapes.interfacesupports Declaration Merging (re-declaring merges properties).typethrows an error if you try to declare it twice.- Use
typewhen you need a union or intersection type.
Done with this concept?
Mark it complete to track your progress. No login needed.