Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring variables of type string index in TypeScript - is there a shortcut?

Tags:

typescript

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] = {};
}
like image 351
Q 4 Avatar asked Dec 26 '22 11:12

Q 4


1 Answers

Yes there is:

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

this is basically an inline declaration of an interface.

like image 111
Rafal Avatar answered Mar 30 '23 01:03

Rafal