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.
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.
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.
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);
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