Let’s delve into the differences between interfaces, types, and classes in TypeScript, along with practical examples for each.
Interfaces
An interface defines a contract that an object must adhere to. It describes the shape of an object by specifying its properties and methods. Here’s an example:
interface Client {
name: string;
address: string;
}
You can express the same contract using type annotations:
type Client = {
name: string;
address: string;
};
Both interface and type can represent similar structures, but interfaces are often preferred when defining object shapes or contracts.
Types
A type in TypeScript allows you to define the shape of data. It includes primitive types, union types, and more. For instance:
type MyNumber = number;
type User = {
id: number;
name: string;
email: string;
};
In the above example, MyNumber is an alias for the number type, and User represents the type definition for a user.
When choosing between type and interface, consider readability and intent. Use type for creating aliases and expressing alternative names for existing types. Use interface when defining contracts or object shapes.
Classes
A class in TypeScript serves as a blueprint for creating objects. It encapsulates data and methods to manipulate that data. Here’s how you can implement a class using both an interface and a type:
// Using an interface
interface Person {
name: string;
greet(): void;
}
class Student implements Person {
name: string;
greet() {
console.log('Hello!');
}
}
// Using a type
type Pet = {
name: string;
run(): void;
};
class Cat implements Pet {
name: string;
run() {
console.log('Running...');
}
}
In summary:
- Use interfaces for defining contracts and object shapes.
- Use types for creating aliases and expressing alternative names for existing types.
- Classes provide blueprints for creating objects and encapsulating behavior.
Remember that the choice between interface and type often depends on your specific use case. Both have their place in TypeScript, and understanding their differences will help you make informed decisions.
Now, Let’s explore the differences between interfaces and types in TypeScript to clarify their purposes:
Interfaces
- Definition:
- An interface defines a contract that an object must adhere to. It describes the shape of an object by specifying its properties and methods.
- Interfaces are designed for extensibility, allowing easy extension and adherence to specific object structures.
- Usage:
- Use interfaces when you want to define contracts or object shapes.
- They are commonly used for describing the structure of objects, classes, and function parameters.
- Example:
TypeScript
interface Client { name: string; address: string; }
Types (Type Aliases)
- Definition:
- A type in TypeScript allows you to define the shape of data. It includes primitive types, union types, and more.
- Type aliases provide an alternative name for an existing type without creating new types.
- Usage:
- Use types when creating aliases or expressing alternative names for existing types.
- They can include implementation details and are versatile for creating union and intersection types.
- Example:
TypeScript
type MyNumber = number; // Alias for number type type User = { id: number; name: string; email: string; }; // Type definition for a user
In summary:
- Interfaces define contracts and object shapes.
- Types create aliases and express alternative names for existing types.
- Choose based on readability, intent, and specific use cases. Both have their place in TypeScript! 🚀
Let’s explore union and intersection types in TypeScript with practical examples:
Union Types
A union type describes a value that can be one of several types. We use the vertical bar (|) to separate each type. Here are some examples:
- String or Number:
type StringOrNumber = string | number; const value: StringOrNumber = "hello"; // Valid const anotherValue: StringOrNumber = 42; // Also valid
- TypeScript
- Process States (Literal Union):
type ProcessStates = "open" | "closed"; const status: ProcessStates = "open"; // Valid
- TypeScript
- Odd Numbers Under Ten (Literal Union):
type OddNumbersUnderTen = 1 | 3 | 5 | 7 | 9; const oddNumber: OddNumbersUnderTen = 3; // Valid
- TypeScript
- A Messy Union (Combining Different Types):
type AMessyUnion = "hello" | 156 | { error: true }; const messyValue: AMessyUnion = { error: true }; // Valid
- TypeScript
Intersection Types
An intersection type combines multiple types into a single type, representing the combination of all types. It is represented using the ampersand (&) operator. Here are some examples:
- Combining Interfaces:
interface A { propA: string; } interface B { propB: number; } let myVariable: A & B = { propA: "Hello", propB: 42, };
- TypeScript
- Merging Properties:
type Named = { name: string }; type Aged = { age: number }; type Person = Named & Aged; const person: Person = { name: "Alice", age: 30, };
- TypeScript
In summary:
- Union types allow flexibility by accepting values of multiple types.
- Intersection types combine multiple types into one, requiring all properties from each type.
'Dev & LLM' 카테고리의 다른 글
High-value AI use cases in business (0) | 2024.04.05 |
---|---|
Travel assistant capabilities use case (1) | 2024.03.27 |
4 Methods of Prompt Engineering (0) | 2024.03.13 |
LLM - How Large Language Models Work & What are Generative AI models? (0) | 2024.03.13 |
Redux vs Redux Toolkit (code example) (0) | 2024.03.09 |
댓글