Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing an indexer in a class in TypeScript

Is it currently possible to implement an indexer on a class in TypeScript?

class MyCollection {    [name: string]: MyType;        } 

This doesn't compile. I can specify an indexer on an interface, of course, but I need methods on this type as well as the indexer, so an interface won't suffice.

Thanks.

like image 889
MgSam Avatar asked Feb 12 '13 20:02

MgSam


People also ask

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.

When should I use indexer?

You typically use an indexer if the class represents a list, collection or array of objects. In your case, you could provide an indexer to provide index-based access to a teacher's students.


1 Answers

You cannot implement a class with an indexer. You can create an interface, but that interface cannot be implemented by a class. It can be implemented in plain JavaScript, and you can specify functions as well as the indexer on the interface:

class MyType {     constructor(public someVal: string) {      } }  interface MyCollection {       [name: string]: MyType; }  var collection: MyCollection = {};  collection['First'] = new MyType('Val'); collection['Second'] = new MyType('Another');  var a = collection['First'];  alert(a.someVal); 
like image 188
Fenton Avatar answered Sep 18 '22 21:09

Fenton