簡體   English   中英

打字稿“TS2339:屬性 'X' 不存在於類型 'Y'”錯誤,即使類型已定義

[英]TypeScript "TS2339: Property 'X' does not exist on type 'Y'" error even though type is defined

在我的代碼中,我試圖訪問React.ReactElement數組元素的type屬性。 即使我已經定義了包含React.ReactElement子元素的數組,我在嘗試訪問數組元素的type屬性時React.ReactElement出錯,除非我將數組元素React.ReactElement類型。

這是我的代碼:

const getChildren = (
    children: (React.ReactChild | React.ReactElement)[]
) => {
    console.log((children[0] as React.ReactElement).type)  // this line works
    console.log(children[0].type)  // this line breaks
}

這是我得到的錯誤:

Property 'type' does not exist on type 'ReactChild | ReactElement<any, string | JSXElementConstructor<any>>'.
  Property 'type' does not exist on type 'string'.  TS2339

我該如何解決這個問題?

我不熟悉 React,但我假設React.ReactChild沒有名為type屬性,這就是您收到錯誤的原因。

Typescript 編譯器不知道您的項目是React.ReactElement類型( React.ReactChildReact.ReactElement ),除非您明確告訴編譯器是哪種類型。 這就是函數中的第一行起作用的原因,因為您明確告訴編譯器在函數中傳遞的參數是React.ReactElement[]或至少數組中的第一個元素是React.ReactElement類型的參數。

如果您知道數組中的元素將始終是React.ReactElement的類型,那么我建議您將函數參數類型更改為

const getChildren = (children: React.ReactElement[]) => {/* ... */}

否則你應該檢查它是哪種類型以避免運行時錯誤:

const getChildren = (children: (React.ReactChild | React.ReactElement)[]) => {
  if (children[0] instanceof React.ReactChild) {
    console.log(children[0].type);
  }
}

暫無
暫無

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

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