-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

The TypeScript Workshop
By :

Index types allow us to create objects that have flexibility as regards the number of properties they may hold. Let's say you have a type that defines an error message, which can be more than one type, and you want the flexibility to add more types of messages over time. Because objects have a fixed number of properties, we would need to make changes to our message code whenever there was a new message type. Index types allow you to define a signature for your type using an interface, which gives you the ability to have a flexible number of properties. In the following example, we will expand on this in the code:
Example04.ts
1 interface ErrorMessage { 2 // can only be string | number | symbol 3 [msg: number ]: string; 4 // you can add other properties once they are of the same type 5 apiId: number 6 }
Link to the preceding example: https://packt.link/IqpWH
First, we create our type signature, as shown in the preceding snippet. Here we have...