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?
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!
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.
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.
Yes, you can use an index signature:
interface MyType { [key: string]: string | boolean | number; } var obj: MyType = { key1: "apple", key2: true, key3: 123 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With