Câu hỏi phỏng vấn Typescript
Câu hỏi

When to use interfaces and when to use classes in TypeScript?

Câu trả lời

In TypeScript, both interfaces and classes are used to define the structure of objects, but they serve different purposes and have distinct characteristics. Here’s a detailed explanation of when to use each:

When to Use Interfaces

  1. Type Checking and Contracts: Interfaces in TypeScript are primarily used for type checking. They define the shape of an object but do not implement any logic. An interface ensures that an object meets a certain contract, which is useful for ensuring consistency across different parts of an application or when interacting with external libraries[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19].

  2. Extensibility: Interfaces are extendable, meaning they can extend other interfaces. This allows you to create a series of related interfaces that build on each other, providing flexibility in how you structure your code[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19].

  3. Declaration Merging: TypeScript interfaces support declaration merging. If you declare an interface more than once, TypeScript will merge the declarations into a single interface. This feature is particularly useful when augmenting existing types or integrating with third-party TypeScript declarations[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19].

  4. Optional Properties: Interfaces allow you to specify optional properties by marking them with a question mark (?). This feature is useful when you want to create types that may have a set of properties, but not all properties are required all the time[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19].

When to Use Classes

  1. Implementation Details: Unlike interfaces, classes in TypeScript are concrete implementations. Use classes when you need to include implementation details, such as methods that contain operational logic. Classes can have constructors, properties, methods, and access modifiers like private, protected, or public[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19].

  2. Instantiation: If you need to create instances using the new keyword, classes are necessary. Classes define a blueprint for creating objects with specific behaviors and initial state[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19].

  3. Inheritance: Classes support traditional inhe...

junior

junior

Gợi ý câu hỏi phỏng vấn

junior

What is Type Erasure in TypeScript?

middle

Explain how and why we could use property decorators in TS?

middle

How to use external plain JavaScript libraries in TypeScript?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào