简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM