1

I have an array of people stored in a multidimensional associative array. Each person belongs to a place and each place belongs to a timezone. I set up my variable like this:

interface AssociativeArray {
    [key: string]: Array<object> | string | number | object;
}

export var mapDB: AssociativeArray[] = [
    {
        timeZone: "HST",
        places: [
            {
                place: "Oahu",
                members: ["Frank", "Jerry", "Pearl"],
            },
            {
                place: "Maui",
                members: ["Susan", "Liana", "Bertha"],
            },
        ],
    },
    {
        timeZone: "PST",
        places: [
            {
                place: "Tahiti",
                members: ["Fido", "Snowy", "Butch"],
            },
        ],
    },
];

To access a specific element in the array, I use the following code:

console.log("The name: ", mapDB[0]["places"][1]["members"][2]);

This code returns the expected value of "Bertha". However, in VS Code, this line is marked with an error message:

Element implicitly has an 'any' type because expression of type '1' can't be used to index type 'string | number | object | object[]'.
  Property '1' does not exist on type 'string | number | object | object[]'

I have tried to write different versions of the "interface" but I cannot seem to get rid of the error message. Can someone help me fix it?

1
  • You'll get the best type for that value without using an explicit type annotation Commented Jun 16, 2023 at 6:11

1 Answer 1

2

The error happens because TypeScript cannot infer the actual types of the nested elements in the multidimensional associative array. You need to be more specific with the types:

interface Place {
  place: string;
  members: string[];
}

interface TimeZone {
  timeZone: string;
  places: Place[];
}

export const mapDB: TimeZone[] = [
  {
    timeZone: "HST",
    places: [
      {
        place: "Oahu",
        members: ["Frank", "Jerry", "Pearl"],
      },
      {
        place: "Maui",
        members: ["Susan", "Liana", "Bertha"],
      },
    ],
  },
  {
    timeZone: "PST",
    places: [
      {
        place: "Tahiti",
        members: ["Fido", "Snowy", "Butch"],
      },
    ],
  },
];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.