簡體   English   中英

打字稿錯誤:元素隱式具有“任何”類型,因為“字符串”類型的表達式不能用於索引類型

[英]Typescript error : Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

我是打字稿的新手,試圖讓一些代碼正常工作簡直是地獄,有人可以幫我解決這個 ts 錯誤。

元素隱式具有“任何”類型,因為“字符串”類型的表達式不能用於索引類型“{”sections.hero“:({sectionData,key}:props)=>元素; }'。 在類型'{'sections.hero': ({ sectionData, key }: props) => Element; }'。

我的代碼:

type sectionDataProps = {
  sectionData: {
    __component: string;
  };
};

// Map Strapi sections to section components
const sectionComponents = {
  'sections.hero': Hero,
};

// Display a section individually
const Section = ({ sectionData }: sectionDataProps) => {
  // Prepare the component
  const SectionComponent = sectionComponents[sectionData.__component];

  if (!SectionComponent) {
    return null;
  }

  // Display the section
  return <SectionComponent data={sectionData} />;
};

// Display the list of sections
const Sections = (props: { sections: [] }) => {
  return (
    <>
      {/* Show the actual sections */}
      {props.sections.map((section) => (
        <Section
          sectionData={section}
          key={`${section.__component}${section.id}`}
        />
      ))}
    </>
  );
};

export default Sections;

在打字稿中,您不允許訪問可能不存在的屬性。 這意味着當有像{ a: number }這樣的類型時,您只能訪問a屬性。 檢查b屬性將是類型錯誤,因為它不存在。


所以你有這種類型的鍵:

__component: string;

這種類型的對象的鍵應該是:

const sectionComponents = {
  'sections.hero': Hero,
};

這意味着此操作只允許使用一個字符串:

sectionComponents[sectionData.__component]

並且該字符串是'sections.hero' ,不允許使用任何其他字符串。

您可以通過幾種方式解決此問題。


首先,您可以將__component屬性的類型更改為:

type sectionDataProps = {
  sectionData: {
    __component: keyof typeof sectionComponents;
  };
};

現在任何string都不是有效值。 字符串必須sectionComponents對象的鍵。

其余的代碼無需修改即可工作。 見游樂場


如果您不想更改道具類型,則必須更改函數的邏輯以確保您不會訪問可能不存在的屬性。

// Display a section individually
const Section = ({ sectionData }: sectionDataProps) => {
  // Prepare the component
  if (sectionData.__component in sectionComponents) {
      const key = sectionData.__component as keyof typeof sectionComponents
      const SectionComponent = sectionComponents[key];
      return <SectionComponent data={sectionData} />;
  }

  return null
};

在這里,我們使用in檢查來查看該對象上是否存在屬性。 然后手動將其轉換為keyof typeof sectionComponents應該是安全的,讓 typescript 知道我們正在證明這個操作是安全的。

看游樂場

暫無
暫無

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

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