簡體   English   中英

TS2739 類型“any[]”缺少來自“JSON”類型的以下屬性:解析、字符串化、[Symbol.toStringTag]

[英]TS2739 Type 'any[]' is missing the following properties from type 'JSON': parse, stringify, [Symbol.toStringTag]

在我的 react-typescript 項目中,當我嘗試將JSON作為道具傳遞時遇到了打字錯誤。

class MainNewsFeed extends React.Component {
    constructor(props: any) {
        super(props);
    }

    render() {
        const bitcoinJson = [...require("./feeds/newsJson.json")];
        return (
            <NewsFeedCol json={newsJson}/>
        );
    }
}

class NewsFeedCol extends React.Component<{ newsJson:JSON },  {}> {
    constructor(props: any) {
        super(props);
        let JsonData = [...props.json]
    }
    render() {
        return (
            <Row>
                <Col sm={12} md={6} lg={4}>
                    <NewsFeedItem index={1}/>
                </Col>
            </Row>
        );
    }
}


/Users/simon/Code/web/thedrewreport/frontend/thedrewreport/src/MainNewsFeed.tsx
TypeScript error in /Users/simon/Code/web/thedrewreport/frontend/thedrewreport/src/MainNewsFeed.tsx(18,26):
Type 'any[]' is missing the following properties from type 'JSON': parse, stringify, [Symbol.toStringTag]  TS2739

    17 |         return (
  > 18 |             <NewsFeedCol json={bitcoinJson}/>
       |                          ^
    19 |         );
    20 |     }
    21 | }

你如何正確處理在這里打字?

似乎您想將newsJson注釋為newsJson類型。 但是, JSON是一個模塊(具有 JSON.parse 和 JSON.stringify),而不是 type 要注釋newsJson屬性,您需要知道您想要的對象的確切形狀,可能將其制作成interface 例如

interface NewsFeedsColProp {
  newsJson: {
     name: string;
     provider: string;
     id: number;
   }
}

class NewsFeedCol extends React.Component<NewsFeedsColProp ,  {}>

請注意字段nameproviderid - 我希望newsJson是具有這 3 個字段的對象。

nameproviderid字段只是我自己編造的; 您需要確定newsJson道具將獲得的數據的確切形狀。

如果您不知道確切的形狀,您可以將newsJsonany類型,或“未知對象”類型: {[key: string]: any} - 這不是一個很好的做法

interface NewsFeedsColProp {
  newsJson: {
    [key: string]: any,
  }
}

// Or
interface NewsFeedsColProp {
  newsJson: any
}

class NewsFeedCol extends React.Component<NewsFeedsColProp ,  {}>

希望我說的有道理

暫無
暫無

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

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