我正在实现 Typescript Array 接口(interface)。我想知道是否有可能为索引定义 get/set。例如:
class MyClass<T> implements Array<T> {
[index: number] : T;
// ... other methods
}
是否可以这样写:
class MyClass<T> implements Array<T> {
get [index: number] () : T {
// implementation
}
set [index: number] (value: T) : void {
// implementation
}
// ... other methods
}
最佳答案
不,重载索引运算符cannot be done在类里面;但是,您可以使用 ES6 Proxy 来定义它, 但许多浏览器尚不支持。
一种替代方法是围绕数组创建一个包装器,以强制人们使用这些方法,您可以在其中放置额外的功能:
class MyContainer<T> {
private items: T[] = [];
get(name: string): T {
// some additional functionality may go here
return this.items[name];
}
set(name: string, value: T) : void {
// some additional functionality may go here
this.items[name] = value;
// or here
}
}
const myContainer = new MyContainer<string>();
myContainer.set("key", "value");
console.log(myContainer.get("key")); // "value"
关于javascript - typescript 索引获取/设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37946249/