Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Class 在TypeScript中的类中实现索引器_Class_Typescript_Indexer - Fatal编程技术网

Class 在TypeScript中的类中实现索引器

Class 在TypeScript中的类中实现索引器,class,typescript,indexer,Class,Typescript,Indexer,当前是否可以在TypeScript中的类上实现索引器 class MyCollection { [name: string]: MyType; } 这不能编译。当然,我可以在接口上指定索引器,但是我需要这种类型的方法以及索引器,所以接口是不够的 谢谢。您不能用索引器实现类。您可以创建接口,但该接口不能由类实现。它可以用普通JavaScript实现,您可以在界面上指定函数和索引器: class MyType { constructor(public someVal:

当前是否可以在TypeScript中的类上实现索引器

class MyCollection {
   [name: string]: MyType;       
}
这不能编译。当然,我可以在接口上指定索引器,但是我需要这种类型的方法以及索引器,所以接口是不够的


谢谢。

您不能用索引器实现类。您可以创建接口,但该接口不能由类实现。它可以用普通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);

对于那些寻找答案的人来说,这是一个老问题:现在可以定义一个索引属性,如:

let查找:{[key:string]:AnyType}

密钥的签名必须是字符串或整数请参见:


否:请参阅和。上述代码现在是合法的,并在的最新版本中编译TypeScript@RichN但是你不能添加方法