简体   繁体   English

在TypeScript中的类中实现索引器

[英]Implementing an indexer in a class in TypeScript

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. 谢谢。

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

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 www.typescriptlang.org上的界面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实现流利的泛型类方法Typescript - Implementing fluent generic class methods Typescript 限制 typescript 类方法实现接口 - Restrict typescript class methods implementing interface TypeScript类实现接口中的私有方法 - Private methods in TypeScript class implementing interface 在类示例中声明索引器。 - Declaring a indexer in a class example. 如何编写一个TypeScript函数来接受将接口实现为参数的类? - How to write a TypeScript function accepting a class implementing an interface as a parameter? 使用 class inheritance 在 TypeScript 中实现 Maybe/Option 类型 - Implementing Maybe/Option type in TypeScript using class inheritance TypeScript 接口可以限制其实现类的属性吗? - Can a TypeScript interface constrain its implementing class's properties? 为什么实现接口的TypeScript类不能分配给扩展接口的通用约束? - Why is this TypeScript class implementing the interface not assignable to a generic constraint extending the interface? TypeScript 0.9.1 CommonJS:正确声明实现外部接口的导出环境类? - TypeScript 0.9.1 CommonJS: correctly declaring exported ambient class implementing external interface? 打字稿-在不实现接口父级的情况下实现接口 - Typescript - implementing an interface without implementing the interfaces parents
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM