[英]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 , {}>
請注意字段name
、 provider
和id
- 我希望newsJson
是具有這 3 個字段的對象。
name
、 provider
和id
字段只是我自己編造的; 您需要確定newsJson
道具將獲得的數據的確切形狀。
如果您不知道確切的形狀,您可以將newsJson
為any
類型,或“未知對象”類型: {[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.