我的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] = {};
}
Run Code Online (Sandbox Code Playgroud)
Raf*_*fal 10
就在这里:
class Foo {
myObjectsByKey: { [index: string]: MyObject; } = {};
}
Run Code Online (Sandbox Code Playgroud)
这基本上是一个接口的内联声明.
| 归档时间: |
|
| 查看次数: |
2617 次 |
| 最近记录: |