DEV Community

protium
protium

Posted on

[Today I learned] Typescript Index Signatures

Days ago I read a post that contained the phrase "Today I learned" in its tittle. So I want to propose this topic as an initiative, the topic Today I Learned or TIL to motivate us all to share those one or two lines of code that did the trick, that command that is what you were looking for and can be useful for others devs.

Edit: It already exists as "todayilearned", cool!

Index Signatures

I was writing some code that interacts with GitHub Gists API. Particularly this endpoint https://developer.github.com/v3/gists/#get-a-single-gist to get a simple gist.
Notice that the field files is an Object instead of an Array. So, how do you safely define types for this find response? We don't know how many properties and which names have each of them.

A small google query directed me to this docs TypeScript Index Signature.

So the types for this Gists Response should be as follow

interface GistFile {
    filename: string;
    type: string;
    language: string;
    raw_url: string;
    size: number;
    truncated: boolean;
    content: string;
  };

interface GistsFiles {
    [key: string]: GistFile
}

interface GistsResponse {
...
files: GistsFiles
... 
}
Enter fullscreen mode Exit fullscreen mode

Now we can access to the response like this

console.log(gistFile.files.somefile.filename);
console.log(gistFile.files['somefile'].filename);
Enter fullscreen mode Exit fullscreen mode

And there we go.
Hope you find this useful.

Top comments (0)