0

In my react-typescript project I am running into a typing error when I try to pass a JSON as a prop.

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 | }

How do you properly handle typing here?

SomethingsGottaGive
  • 1,646
  • 6
  • 26
  • 49
  • Does this answer your question? [How do I initialize a TypeScript Object with a JSON-Object?](https://stackoverflow.com/questions/22885995/how-do-i-initialize-a-typescript-object-with-a-json-object) – dee Jul 11 '21 at 16:49

1 Answers1

3

It seems like you want to annotate the newsJson to be of type object. However, JSON is a module (which has JSON.parse and JSON.stringify), not a type. To annotate newsJson attribute, you will need to know the exact shape of the object that you want, probably make it into an interface. For example

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

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

Note the fields name, provider, and id - I am expecting the newsJson to be an object with these 3 fields.

The name, provider, and id fields are just made-up things of mine; you need to determine the exact shape of the data that your newsJson prop is going to get.

If you can't know the exact shape, you can type newsJson as any type, or "unknown-object" type: {[key: string]: any} - which is not really a good practice

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

// Or
interface NewsFeedsColProp {
  newsJson: any
}

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

Hope I am making sense

Bao Huynh Lam
  • 974
  • 4
  • 12