Questions
What is the difference between an `interface` and a `type` in TypeScript?
The Scenario
You are a frontend engineer at a social media company. You are writing a new feature that needs to define the shape of an object.
You are not sure whether to use an interface or a type to define the shape of the object.
The Challenge
Explain the difference between an interface and a type in TypeScript. What are the pros and cons of each approach, and which one would you choose for this use case?
A junior engineer might think that they are interchangeable. They might not be aware of the difference in features or the design implications of choosing one over the other.
A senior engineer would be able to provide a detailed explanation of the differences between an `interface` and a `type`. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in a given situation.
Step 1: Understand the Key Differences
| Feature | interface | type |
|---|---|---|
| Extensibility | An interface can be extended by another interface. | A type can be extended using an intersection. |
| Declaration Merging | An interface can be defined multiple times and the definitions will be merged. | A type cannot be defined multiple times. |
| Use Cases | When you need to define the shape of an object. | When you need to define a union, a tuple, or a primitive type alias. |
Step 2: Choose the Right Tool for the Job
For our use case, we should use an interface. This is because we are defining the shape of an object, and an interface is the best tool for this job.
In general, you should use an interface when you are defining the shape of an object, and a type when you are defining a union, a tuple, or a primitive type alias.
Step 3: Code Examples
Here are some code examples that show the difference between the two approaches:
interface:
interface MyInterface {
myProperty: string;
}
const myObject: MyInterface = {
myProperty: 'myValue'
};type:
type MyType = {
myProperty: string;
};
const myObject: MyType = {
myProperty: 'myValue'
}; Practice Question
You want to create a new type that can be either a `string` or a `number`. Which of the following would you use?