DEV Community

protium
protium

Posted on

3 3

[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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay