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}
?
The index signature is a fitting way to handle objects with properties we know nothing about. Its syntax describes a regular property, but instead of writing a standard property name, we define the type of keys and the properties.
Defining Classes. To declare a class, we use the class keyword. For example, to declare a simple class, we can write: Class declarations aren't hoisted so they can't be used before they're defined in the code — the TypeScript compiler will not automatically pull them up to the top.
The error "Property is incompatible with index signature" occurs when a property is not compatible with the specified type of the index signature. To solve the error, change the type of the property or use a union to update the type in the index signature.
The indexing type is itself a type, so we can use unions, keyof , or other types entirely: type I1 = Person ["age" | "name"]; type I1 = string | number. type I2 = Person [keyof Person ]; type I2 = string | number | boolean.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With