How to define a TypeScript class which has an index signature?
How to define a TypeScript class which has an index signature?
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:
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:
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.