When to Use Type or Interface With TypeScript
In this article, I’ll be going over the differences between type
and interface
declarations in TypeScript. This is a question I often get asked at work and I thought it would be a good idea to make it into an article to share.
Types
When referring to a Type created with the type
keyword, what we are really referring to are Type Aliases. Type is often used to describe Type Aliases because the keyword used to define them is type
.
type Dog = {
breed: string
name: string
age: number
}
type ShirtSize = "small" | "medium" | "large"
A Type Aliases is a name given to a Type. Giving a name to a Type allows you to share it across your application easily.
Interface
Interfaces or Interface Declarations are another way to reference a Type.
interface Dog {
breed: string
name: string
age: number
}
Key Differences
Type Aliases and Interface Declarations are similar in their behavior. The main distinction is Interface Declarations can be added to after their declaration, while Type Declarations cannot.
interface Dog {
name: string
age: number
}
interface Dog {
height: string
}
const dog: Dog = {
name: "fido"…