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

What is the difference between Classes and Interfaces in Typescript?

Câu trả lời

In TypeScript, both classes and interfaces are foundational concepts used to structure and type-check code, but they serve different purposes and have distinct characteristics.

Classes

A class in TypeScript is a blueprint for creating objects with specific properties and methods. It encapsulates data for the object and can include functionalities. Classes are used to instantiate new objects using the new keyword, allowing for the creation of multiple instances, each with their own set of data and behaviors.

  • Properties and Methods: Classes can contain properties and methods. Properties define the data elements, and methods define the actions the class can perform.
  • Inheritance: TypeScript classes support inheritance, allowing one class to extend another. This means a class can inherit properties and methods from another class.
  • Constructors: Classes can have constructors, special methods called when a new object instance is created. Constructors are used for initializing object properties.
  • Type Checking: Classes are involved in type checking at runtime and can include various access modifiers like public, private, and protected which control the accessibility of the class members.

Example of a TypeScript class:

typescript Copy
class Animal {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
    move(distance: number) {
        console.log(`${this.name} moved ${distance}m.`);
    }
}

Interfaces

An interface in TypeScript is a structure that defines the shape of an object but does not implement any real functionality. Interfaces are used to type-check whether an object fits a certain structure. They are purely a compile-time construct and do not generate any JavaScript code.

  • Type-checking: Interfaces are used for type-checking; they define the properties, types, and methods that an object should have.
  • No Instantiation: Interfaces cannot be instantiated directly. They are used to define...
junior

junior

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

junior

What is a TypeScript Map file?

junior

What is Interface in TypeScript?

expert

What does the tsconfig option lib do?

Bình luận

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

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