Interfaces vs Types in TypeScript
What’s the difference between these statements (interface
vs type
) in TypeScript? You want to type your code, but you’re not sure exactly which syntax to use 🥴.
Let’s say you got some code to name a type of object:
// defining a type with interface
interface X {
y: number;
z: string;
}
// defining a type with type
type A = {
b: number;
c :string;
}
They both can declare types, and you may have used a mixture in your codebase without fully knowing (or caring) what the differences are; but hopefully we can get a clearer picture after doing some reading and research.
Defining interface and type
You can declare types in TypeScript directly in type annotations, and although it’s convenient, you’ll most likely use the same type more than once and it'll be easier to reference it by name once you have it defined.
// variable type with annotation
const name: string = 'Steve'
// variable type with a Type Alias
type Point = {
x: number;
y: number;
}
// interface declaration to type an object
interface Point {
x: number;
y: number;
}
Similarities
Both Type aliases and interfaces are similar in a lot of ways, and for the most part you can choose between them at your discretion. The main difference I’ve seen is that an interface
is both 'easier' (your opinion may differ) to extend and can be recreated; the latter may or may not be a bad thing 😅.
// both can inherit/extend types
interface Animal {
name: string;
}
interface Dog extends Animal {
tail: boolean;
}
// extend via types
type Animal = {
name: string;
}
type Dog = Animal & {
tail: boolean;
}
Difference/s
With interface
, you can merge declarations by simply declaring interface again; whether that's a good thing or not is up to you 🤷♂️.
interface Person {
name: string;
}
interface Person {
age: number;
}
const steve: Person = {
name: 'steve',
age: 0 // will error out without an age!
};
Try that with type
and you'll get an error.
There are more differences, no doubt; the TypeScript docs go into further detail.
When to Use Which
I've seen experts go both ways on this, so there isn't really a clearcut answer; the consistent answer I see the most is to be consistent with your codebase - which I can wholeheartedly agree with.
Personally, I prefer type
.