Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define a Typescript class which has an index signature?

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}?

like image 664
Chris T Avatar asked Aug 13 '15 00:08

Chris T


People also ask

What is TypeScript index signature?

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.

How do you define a class in TypeScript?

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.

Is incompatible with index signature?

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.

What is index type in TypeScript?

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.


1 Answers

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; } 
like image 65
Ryan Cavanaugh Avatar answered Oct 20 '22 05:10

Ryan Cavanaugh