Interfaces vs Types
In TypeScript, a key idea is that checking types is all about how things look. This is also known as “duck typing” or “structural subtyping”. In TypeScript, there are two options for define types which are Types and Interfaces are used to make these types. They’re a strong tool for setting rules in your code and agreeing on rules with code outside of your project, thereby reducing errors and improving readability.
What is a Interface?
Interfaces are used to describe the shape of objects, and can be extended by other interfaces. Interfaces are mainly used to define class structures but can also be used with functions.
// Define an object interface
interface User {
name: string;
age: number;
}
// Interface inheritance
interface Admin extends User {
admin: boolean;
}
// Interface in a function
function greet(person: User) {
return “Hello “ + person.name
}
// Ensure class conforms to an interface via implements class
Greet implements User {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
What is a Types?
Full name is “type alias” and are used to define names to type literals. In which supports more rich type-system features then interfaces.
// Define a type
type User = {
name: string;
age: number;
}
type Person = User & {
admin: boolean;
}
// Types in a function
function greet(person: User) {
return “Hello “ + person.name
}
Differences between interfaces and types
Primitive Types
Primitive types are inbuilt types in TypeScript. JavaScript has a total of seven primitives those being string, number, boolean, null, undefined, bigint(less common), and symbol(less common).
Union Types
A Union Type is a type formed from two or more other types, representing values that may be any one of those types listed. Each types are referred to as union’s members.
type Transport = “Car” | “Bus” | “Bike” | “Foot”
Types vs Interfaces
Some key points when thinking of using types over interfaces are:
- Interfaces are limited to only describing object shapes.
- Type cannot be re-opened to add new properties vs an interface which is always extendable.
- Interfaces can be extended by declaring it multiple times to other classes.
- If you are dealing with performance, in critical types interface comparison checks can be faster.