我的TypeScript应用程序经常使用一种模式,其中我有一组数据(一个对象),它存储在一个字符串索引(另一个对象)中,以便通过键进行快速查找。在TypeScript中实现这个很容易,但需要两个接口定义(用于数据对象和字符串索引器对象)。我发现我的代码中充斥着这些字符串索引器接口,它们并没有增加多少价值,因此正在寻求一种使代码更易读/可维护的方法。
是否有一种声明类型为字符串索引器的变量的内联方式,就像我们可以使用数组(数字索引器)一样?以下是我正在做的事情以及我想要做的事情的示例:
是否有一种声明类型为字符串索引器的变量的内联方式,就像我们可以使用数组(数字索引器)一样?以下是我正在做的事情以及我想要做的事情的示例:
interface MyObject {
foo: string;
bar: string;
}
// is there a way to not have to define this interface?
interface MyObjectByKey {
[index: string]: MyObject;
}
class Foo {
// this works: inline declaration of variable of type numeric indexer
myObjectsByIndex: MyObject[] = [];
// this works: variable of type string indexer, but requires extra interface
myObjectsByKey: MyObjectByKey = {};
// wish I could do something like this ... (can I?)
myObjectsByKeyWish: MyObject[index: string] = {};
}