Implementing an indexer in a class in TypeScript

可紊 提交于 2019-11-27 17:12:50

问题


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



来源:https://stackoverflow.com/questions/14841598/implementing-an-indexer-in-a-class-in-typescript

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