This is a common interview question, especially for Junior and Middle positions. In general, what they usually want to hear in an interview is interface merging.
Let’s break it down with an example:
interface IUser {
name: string;
email: string;
}
interface IUser {
age: number;
}
// TypeScript will merge these two interfaces
// This is now a single interface, so IUser will also expect the age field.
const user: IUser = {
name: 'Test',
email: 'test@test.com',
age: 30,
}
If you try the same approach with a type, you will get an error. When answering this question, it would be a bonus to mention when it’s better to use type vs interface:
- Interface is better used to describe the structure of objects and classes, as intended in
OOP. - For everything else, it’s more appropriate to use type, especially in the context of building complex types:
union,utility types,function signatures…