I am trying to use a multidimensional associative array that was passed from php to the frontend so I have created a new type as follows:
type AssociativeArray<T = unknown> = { [key: string]: AssociativeArray<T> | T | undefined | T[] };
When I try to compile the following code:
type AssociativeArray<T = unknown> = { [key: string]: AssociativeArray<T> | T | undefined | T[] };
const exampleStatusJSON: AssociativeArray<string> = {
available: "true",
username: "Jean-loup",
house: {
room: {
name: "Highcrest",
},
}
};
if ((typeof (exampleStatusJSON["house"]) !== "undefined") &&
(typeof (exampleStatusJSON["house"]["room"]) !== "undefined") &&
(typeof (exampleStatusJSON["house"]["room"]["name"]) !== "undefined")) {
console.log("OK");
}
typescript throws an error in the second and third condition:
Element implicitly has an 'any' type because expression of type '"room"' can't be used to index type 'string | AssociativeArray<string> | string[]'.
Property 'room' does not exist on type 'string | AssociativeArray<string> | string[]'.(7053)
What would be the best way to describe such arrays in typescript?