在TypeScript中的类中实现索引器 [英] Implementing an indexer in a class in TypeScript

查看:744
本文介绍了在TypeScript中的类中实现索引器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前是否可以在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.

谢谢。

推荐答案

不能使用索引器实现类。您可以创建一个接口,但该接口不能由类实现。它可以在纯JavaScript中实现,您可以在界面上指定函数以及索引器:

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

这篇关于在TypeScript中的类中实现索引器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆