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?
It seems like you want to annotate the newsJson
to be of type object. However, JSON
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.