4

我的 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] = {};
}
4

1 回答 1

10

就在这里:

class Foo {
    myObjectsByKey: { [index: string]: MyObject; } = {};
}

这基本上是一个接口的内联声明。

于 2013-01-09T12:48:00.047 回答