본문 바로가기
Dev & LLM

Typescript - interface, type, class 이해하기

by 쉽게 이해하는 테크 2024. 3. 9.
728x90
반응형

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:

TypeScript
 
interface Client {
  name: string;
  address: string;
}

 

 

You can express the same contract using type annotations:

TypeScript
 
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:

TypeScript
 
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:

TypeScript
 
// 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

  1. 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.
  2. 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.
  3. Example:
    TypeScript
    interface Client {
      name: string;
      address: string;
    }
    
     

Types (Type Aliases)

  1. 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.
  2. 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.
  3. 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:

  1. String or Number:
    type StringOrNumber = string | number;
    const value: StringOrNumber = "hello"; // Valid
    const anotherValue: StringOrNumber = 42; // Also valid
    
     
  2. TypeScript
     
  3. Process States (Literal Union):
    type ProcessStates = "open" | "closed";
    const status: ProcessStates = "open"; // Valid
    
     
  4. TypeScript
     
  5. Odd Numbers Under Ten (Literal Union):
    type OddNumbersUnderTen = 1 | 3 | 5 | 7 | 9;
    const oddNumber: OddNumbersUnderTen = 3; // Valid
    
     
  6. TypeScript
     
  7. A Messy Union (Combining Different Types):
    type AMessyUnion = "hello" | 156 | { error: true };
    const messyValue: AMessyUnion = { error: true }; // Valid
    
     
  8. 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:

  1. Combining Interfaces:
    interface A {
      propA: string;
    }
    
    interface B {
      propB: number;
    }
    
    let myVariable: A & B = {
      propA: "Hello",
      propB: 42,
    };
    
     
  2. TypeScript
     
  3. Merging Properties:
    type Named = { name: string };
    type Aged = { age: number };
    
    type Person = Named & Aged;
    const person: Person = {
      name: "Alice",
      age: 30,
    };
    
     
  4. 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.
728x90
반응형

댓글