I have an interface type called IRawParams
which simply specifies a string
key and any
vals.
interface IRawParams {
[key: string]: any
}
I have a class, ParamValues
which contains some behavior on top of keys/values. I'd like to specify that the ParamValues
class implements IRawParams
interface.
class ParamValues implements IRawParams {
parseFromUrl(urlString: string) {
Parser.parse(urlString).forEach(item => this[item.key] = item.val);
}
}
// so I can do something like this
var params = new ParamValues();
params.parseFromUrl(url);
var userId = params.userId;
When I attempt this, I get a compiler error:
error TS2420: Class 'ParamValues' incorrectly implements interface 'IRawParams'. Index signature is missing in type 'ParamValues'.
Can I get my class to implement the IRawParams Interface, or otherwise get Typescript to allow instances of my class to be compatible with an indexed type {[key: string]: any}
?
To define a class with an index signature, just write the index signature in the class:
interface IRawParams {
[key: string]: any
}
class Foo implements IRawParams {
[k: string]: any;
}