Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

typescript access object dynamically

I got this error in typescript

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 

when I try to access object property dynamically:

import React, { useState } from "react";

const cities = {
  ny: {
    label: "New York"
  },
  ld: {
    label: "London"
  }
};

export default function App() {
  const [city, setCity] = useState<string>("ny");

  console.log(cities[city].label); //what's wrong here

  return (
    <div className="App">
      hi
    </div>
  );
}

any clue how to get rid of such error?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You say that cities have only two keys when you declare it: "ny" and "ld" but then you allow any city to be a key of your cities element.

Changing:

useState<string>

to

useState<"ny" | "ld">("ny")

should solve your issue.

If you want to allow more city you could also go with this approach:

type City = {
  [key: string]: {
    label: string;
  };
};

const cities: City = {
  ny: {
    label: "New York",
  },
  ld: {
    label: "London",
  },
};

and keep your useState.

Finally you could dynamically generate the possible keys based on your cities const using:

const [city, setCity] = useState<keyof typeof cities>("ny");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading