簡體   English   中英

反應 typescript - 元素隱式具有“任何”類型,因為使用國家標志圖標時,“字符串”類型的表達式不能用於索引類型

[英]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

應用程序.tsx

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

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

個人.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;

在行

const Flag = Flags[flagNationCode];

, typescript 在這里拋出錯誤

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)

有可能修復嗎?

代碼沙盒
https://codesandbox.io/s/react-typescript-forked-j05w6x?file=/src/Person.tsx

您需要確保flagNationCode是 Flag 的鍵而不是任何字符串。 為此,您可以將 flagNationCode 定義為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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM