My TypeScript application makes frequent use of a pattern where I have a set of data (an object) that is stored in a string index (another object) for quick lookup by key. Implementing this in TypeScript is easy, but requires two interface definitions (for the data object, and for the string indexer object). I'm finding that my code is becoming littered with these string indexer interfaces, which don't add much value, and am seeking a way to have more readable / maintainable code.
Is there a way to declare a variable of type string indexer inline, much like we can do with an array (a numeric indexer)? Here's an example of what I'm doing, and what I would like to do:
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] = {};
}
Yes there is:
class Foo {
myObjectsByKey: { [index: string]: MyObject; } = {};
}
this is basically an inline declaration of an interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With