在 TypeScript 的类中实现索引器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14841598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Implementing an indexer in a class in TypeScript
提问by MgSam
Is it currently possible to implement an indexer on a class in TypeScript?
目前是否可以在 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.
谢谢。
回答by Fenton
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:
您不能使用索引器实现类。您可以创建接口,但该接口不能由类实现。它可以用纯 JavaScript 实现,您可以在界面上指定函数和索引器:
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);
回答by Arjan
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};
let lookup : {[key:string]:AnyType};
the signature of the key must be either string or integer see:
密钥的签名必须是字符串或整数,请参阅: