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

What is Decorators in TypeScript?

Câu trả lời

Decorators in TypeScript are a special kind of declaration that can be applied to classes, methods, accessor properties, or parameters. They are functions that are prefixed with the @ symbol, where the expression following the @ symbol must evaluate to a function that will be called at runtime with information about the decorated declaration. Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members. They can be used to modify or replace class and member definitions, including properties and methods.

Decorators serve various purposes, such as modifying the behavior of a method or property, adding metadata, or even defining new properties or methods at runtime. They are particularly useful for writing declarative code and can be used to enhance the functionality of classes in a reusable way. TypeScript decorators are inspired by similar features in other languages, such as annotations in Java and decorators in Python.

To enable experimental support for decorators in TypeScript, you need to enable the experimentalDecorators compiler option either on the command line or in your tsconfig.json file. This is necessary because decorators are part of an evolving feature set that may change in future versions of TypeScript.

Here's a simple example of a class decorator in TypeScript:

typescript Copy
function sealed(constructor: Function) {
    Object.seal(constructor);
    Object.seal(constructor.prototype);
}

@sealed
class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
  ...
junior

junior

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

middle

How to add types to an interface from another interface or extend types in TypeScript?

junior

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

expert

What is the need of --incremental flag in TypeScript?

Bình luận

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

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