The object structure you are using, like {something: 1}
, does not match the type {type: string}
. The reason is that the former does not have a key named type
with a value of type string
. When iterating through the message
array, attempting to access the type
property results in undefined
. Since each item in the array is an object, it is displayed within curly braces due to this misclassification. The use of JSON.parse()
generates values of the very flexible and permissive any
type, causing this misclassification only to manifest at runtime.
To accurately describe your object type, it should have a single dynamically keyed property with a value of type number
(based on the provided example). Implementing such a structure with just one unknown key can be challenging in TypeScript.
An alternative approach is utilizing an index signature like {[k: string]: number}
, signifying "an object type containing dynamic keys of type string
whose values are number
s." While this may closely align with your requirements, it contrasts in terms of unspecified keys quantity; an index signature allows any number of unspecified keys, while you specified just one. Proceed by ensuring to extract only the first (and sole) key.
I would suggest employing a type assertion to convey to the compiler the anticipated structure of the parsed JSON:
const body = JSON.parse(geison) as { message: Array<{ [k: string]: number }> };
Subsequently, for each element in the message
array (now recognized by the compiler as an array of dictionaries-of-numbers), retrieve its presumed solitary key by obtaining the initial output from Object.keys()
:
body.message.forEach(item => {
const key = Object.keys(item)[0];
console.log(key);
console.log(item[key]);
});
This adjustment should lead to the expected behavior. Best of luck with your implementation!
Link to Interactive Code Playground