Friday, November 3, 2017

TypeScript Index Signatures

I love TypeScript and how it helps me writing better JavaScript applications. However sometimes I struggle with the dynamic world that JavaScript has to offer and the fight for type safety that TypeScript adds to the mix.

A situation I had was where I had some objects each sharing the same set of properties. However in some situations extra metadata was added depending on the customer(it’s a multitenant solution). So I created an interface for all the shared properties, but what should I do with the (possible) extra metadata? Adding so many different extra properties on the interface and making them optional sounded not ideal?

TypeScript allows you to add extra properties to specific objects with the help of index signatures. Adding an index signature to the interface declaration allows you to specify any number of properties for different objects that you are creating.

An example:

1 comment:

meenumaga said...

These ways are very simple and very much useful, as a beginner level these helped me a lot thanks fore sharing these kinds of useful and knowledgeable information.
Self Employment Tax
Tax Preparation Services
Tax Accountant
Tax Consultant
Tax Advisor