Intro ✨
In TypeScript, both types and interfaces are used to define custom data structures and enforce type safety. While they have some similarities, there are also differences in their syntax and capabilities. Here's a comparison of types and interfaces in TypeScript
Types ⌨️
Types in TypeScript are defined using the
type
keyword, followed by the name and the type definition.Types allow you to create aliases for existing types or define new types based on combinations of existing ones.
Types can be used with the union (
|
) and intersection (&
) operators to create complex types.Types are more flexible and can represent primitive types, object types, function types, and more.
Types are generally used when defining union types, intersection types, and literal types, or when creating complex type transformations using mapped types or conditional types.
Using Types (Examples)🔗
Type Aliases
Type aliases allow you to create custom names for existing types, making your code more readable and expressive.
type ID = number;
type Name = string;
const userId: ID = 1;
const userName: Name = "John Doe";
Union Types
Union types allow you to specify that a value can be one of several types.
type Status = "pending" | "active" | "inactive";
const userStatus: Status = "active";
Intersection Types
Intersection types allow you to combine multiple types into a single type.
type Admin = {
id: number;
role: "admin";
};
type Employee = {
id: number;
role: "employee";
};
type AdminEmployee = Admin & Employee;
const adminEmployee: AdminEmployee = {
id: 1,
role: "admin",
};
Literal Types
Literal types allow you to specify the exact values that a variable can have.
type Color = "red" | "green" | "blue";
function setColor(color: Color) {
// ...
}
setColor("red");
setColor("green");
setColor("blue");
// setColor("yellow"); // Error: Argument of type '"yellow"' is not assignable to parameter of type 'Color'
Interfaces 🧩
Interfaces in TypeScript are defined using the
interface
keyword, followed by the name and the shape of the object.Interfaces allow you to define the structure of an object, including property names, types, and optional properties.
Interfaces can extend other interfaces using the
extends
keyword, enabling code reuse and inheritance-like behavior.Interfaces can be implemented by classes, providing a way to enforce that a class adheres to a specific contract.
Interfaces are typically used when defining object shapes, specifying contracts, or implementing object-oriented principles.
Using Interfaces (Examples)🔗
Basic Interface
Interfaces allow you to define the structure of an object, specifying the property names and types.
interface Person {
name: string;
age: number;
}
const person: Person = {
name: "John Doe",
age: 30,
};
Optional Parameters
Interfaces can have optional properties denoted by the '?' symbol
interface User {
id: number;
name: string;
email?: string;
}
const user: User = {
id: 1,
name: "John Doe",
};
Interface Extending Another Interface
Interfaces can extend other interfaces, inheriting their properties and adding new ones.
interface Shape {
color: string;
}
interface Circle extends Shape {
radius: number;
}
const circle: Circle = {
color: "red",
radius: 5,
};
Interface Implementation in Classes
Interfaces can be implemented by classes to enforce that the class adheres to a specific contract.
interface Animal {
makeSound(): void;
}
class Dog implements Animal {
makeSound() {
console.log("Woof!");
}
}
const dog = new Dog();
dog.makeSound(); // Output: "Woof!"
When to use Types or Interfaces 🤔
Use types when you need flexibility and want to define complex types or create aliases for existing ones.
Use interfaces when you want to define the shape of objects, specify contracts, or enable class implementation checks.
In general, there is no strict rule for choosing between types and interfaces. It often depends on personal preference, project requirements, and code style guidelines.
⭐ Summary
In TypeScript, both types and interfaces are powerful tools used to define custom data structures and enforce type safety.
Types are created using the type
keyword, allowing you to create aliases for existing types or define new types based on combinations of existing ones. Types are more flexible and can represent various types, including primitive types, object types, and function types.
On the other hand, interfaces are defined using the interface
keyword, specifying the shape of an object, including property names, types, and optional properties. Interfaces can extend other interfaces and can be implemented by classes, enabling code reuse and enforcing specific contracts. Choosing between types and interfaces depends on your specific use case and coding style, providing the flexibility needed to create robust and maintainable TypeScript code.
Stay tuned for more episodes in the TypeScript 101 series, where we will continue exploring advanced TypeScript features and techniques to level up your TypeScript development skills!
Happy coding! 😉