DEV Community

Cover image for TypeScript Best Practices — Using Index Signature
Stephen Gbolagade
Stephen Gbolagade

Posted on

TypeScript Best Practices — Using Index Signature

Another day to escape from any h€ll in your TypeScript's project.

When fetching data, the best way to leverage the benefit of TypeScript's intelliSense is to define the types or interfaces of your data response.

That is, if you know the structure or the response schemas.

But in the case we are not sure of how the backend structured the response, we often default to using any just to tell eslint to keep quite.

TypeScript's Index Signature may be helpful in that case instead of any.

The best thing about Index Signature is that you can extend the data type as much as you like.

For instance, if you know the response also have an array or object value, you can explicitly define it when catching other key-value pairs at once.

Below is a snippet comparing Index Signature and any

Index Signature in TypeScript

Note again that the best way is to define your response schemas explicitly if you know how it is structured, otherwise use Index Signature or generics which I will be discussing next.

Index is helpful, try it out.

Top comments (0)