Interface for an associative array of objects in TypeScript

I have an object like this:

var obj = { key1: "apple", key2: true, key3: 123, . . . key{n}: ... } 

So obj can contain any number of named keys, but all values ​​must be either strings, or bool, or a number.

How to declare an obj type as an interface in TypeScript? Is it possible to declare an associative array (or variational tuple) of type union or something similar?

+13
source share
1 answer

Yes, you can use an index signature :

 interface MyType { [key: string]: string | boolean | number; } var obj: MyType = { key1: "apple", key2: true, key3: 123 }; 
+20
source

All Articles