Implementing an indexer in a class in TypeScript

2020-02-10 01:33发布

问题:

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.

回答1:

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


回答2:

This is an old question, for those looking for the answer: now it's possible to define a indexed property like:

let lookup : {[key:string]:AnyType};

the signature of the key must be either string or integer see:

Interfaces on www.typescriptlang.org