How to define a TypeScript clas...
How to define a TypeScript clas...
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:
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:
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:
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
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào