[英]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.ReactChild
或React.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.