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

How to define a TypeScript clas...

Câu trả lời

To define a TypeScript class with an index signature, you can directly include the index signature within the class body. An index signature specifies the type of keys and values that instances of the class can hold. Here's a general syntax for including an index signature in a TypeScript class:

typescript Copy
class MyClass {
  [key: string]: any;
}

This syntax declares a class MyClass with an index signature that allows string keys and values of any type. This means you can dynamically set and access properties of instances of MyClass using string keys, and these properties can hold values of any type.

For a more specific example, if you want to ensure that all values in the class instance are of a specific type, say number, you can define the index signature as follows:

typescript Copy
class MyClass {
  [key: string]: number;
}

In this case, MyClass instances can only hold number values, and attempting to assign values of other types will result in a TypeScript compilation error.

It's also possible to implement an interface with an index signature in a class. For example, if you have an interface IRawParams that specifies a string key and any values:

typescript Copy
interface IRawParams {
  [key: string]: any;
}

And you want a class ParamValues to implement this interface and include some behavior on top of the keys/values, you can do so as follows:

typescript Copy
class ParamValues implements IRawParams {
  [key: string]: any;

  parseFromUrl(urlString: string) {
    // Implementation that parses the URL and sets key-value pairs on this instance
  }
}

In this example, th...

senior

senior

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

junior

What is getters/setters in TypeScript?

middle

What is the unique symbol is used for?

junior

Could we use TypeScript on backend and how?

Bình luận

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

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