Implementing an indexer in a class in TypeScript

对着背影说爱祢 提交于 2019-11-29 02:54:05

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!