Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface for associative object array in TypeScript

I have an object like so:

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

So obj can contain any number of named keys, but the values must all be either string, bool, or number.

How do I declare the type of obj as an interface in TypeScript? Can I declare an associative array (or variadic tuple) of a union type or something similar?

like image 350
prmph Avatar asked Jul 05 '16 22:07

prmph


People also ask

How do you define an array of objects in TypeScript?

To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!

How do you define object of objects type in TypeScript?

To define an object of objects type in TypeScript, we can use index signatures with the type set to the type for the value object. const data: { [name: string]: DataModel } = { //... }; to create a data variable of type { [name: string]: DataModel } where DataModel is an object type.

Does JS support associative array?

JavaScript does not support associative arrays. You should use objects when you want the element names to be strings (text). You should use arrays when you want the element names to be numbers.


1 Answers

Yes, you can use an index signature:

interface MyType {     [key: string]: string | boolean | number; }  var obj: MyType = {     key1: "apple",     key2: true,     key3: 123 }; 
like image 181
David Sherret Avatar answered Oct 05 '22 10:10

David Sherret