目前是否可以在TypeScript中的类上实现索引器?
class MyCollection {
[name: string]: MyType;
}
这不能编译。当然,我可以在接口上指定索引器,但除了索引器之外,我还需要此类型的方法,因此接口是不够的。
谢谢。
发布于 2013-02-13 18:21:05
不能使用索引器实现类。您可以创建接口,但该接口不能由类实现。它可以用普通的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);
发布于 2017-07-10 22:00:59
对于那些正在寻找答案的人来说,这是一个古老的问题:现在可以定义一个索引属性,比如:
let lookup : {[key:string]:AnyType};
密钥的签名必须是字符串或整数,请参阅:
发布于 2021-09-28 08:09:24
在类中定义索引属性getter/setter是不可能的,但您可以使用Proxy以如下方式“模拟”它
class IndexedPropSample {
[name: string | symbol]: any;
private static indexedHandler: ProxyHandler<IndexedPropSample> = {
get(target, property) {
return target[property];
},
set(target, property, value): boolean {
target[property] = value;
return true;
}
};
constructor() {
return new Proxy(this, IndexedPropSample.indexedHandler);
}
readIndexedProp = (prop: string | symbol): any => {
return this[prop];
}
}
var test = new IndexedPropSample();
test["propCustom"] = "valueCustom";
console.log(test["propCustom"]); // "valueCustom"
console.log(test.readIndexedProp("propCustom")); // "valueCustom"
console.log(test instanceof IndexedPropSample); // true
console.log(Object.keys(test)); // ["propCustom", "readIndexedProp"]
您可以在Typescript Playground中尝试
https://stackoverflow.com/questions/14841598
复制相似问题