react typescript - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type when using country-flag-icons

Viewed 36

App.tsx

import "./styles.css";
import Person from "./Person";

export default function App() {
  return (
    <div className="App">
      <Person flagNationCode="HK" />
    </div>
  );
}

Person.tsx

import Flags from "country-flag-icons/react/3x2";

const Person = ({ flagNationCode }: { flagNationCode: string }) => {
  const Flag = Flags[flagNationCode];
  return (
    <div className="person-footer">
      <div className="info">
        <div className="label">{flagNationCode}</div>
        <div className="value">
          <Flag />
        </div>
      </div>
    </div>
  );
};

export default Person;

In the line

const Flag = Flags[flagNationCode];

, typescript throws error here

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof import("/sandbox/node_modules/country-flag-icons/react/3x2/index")'.
  No index signature with a parameter of type 'string' was found on type 'typeof import("/sandbox/node_modules/country-flag-icons/react/3x2/index")'.ts(7053)

Is it possible to fix?

Codesandbox
https://codesandbox.io/s/react-typescript-forked-j05w6x?file=/src/Person.tsx

1 Answers

you would need to ensure flagNationCode is a key of Flag rather than any string. For that you could define flagNationCode as keyof typeof Flags:

import Flags from "country-flag-icons/react/3x2";

const Person = ({ flagNationCode }: { flagNationCode: keyof typeof Flags }) => {
  const Flag = Flags[flagNationCode];
  return (
    <div className="person-footer">
      <div className="info">
        <div className="label">{flagNationCode}</div>
        <div className="value">
          <Flag />
        </div>
      </div>
    </div>
  );
};

export default Person;
Related