Objects & Interfaces

Two ways to define an object's shape, and the subtle difference between them.

TypeScript4 min readConcept 6 of 54

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.

// 1. Initial declaration
interface User {
name: string;
}

// 2. Attempt to declare the exact same name again
interface User {
age: number;
}

Declaration Merged

TypeScript quietly merges both blocks. User now safely requires both name and age.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What happens if you declare two 'interface' blocks with the exact same name in the same scope?

Remember this

  • interface and type can both describe object shapes.
  • interface supports Declaration Merging (re-declaring merges properties).
  • type throws an error if you try to declare it twice.
  • Use type when you need a union or intersection type.

Done with this concept?

Mark it complete to track your progress. No login needed.