javascript - TS2739 类型“any[]”缺少类型“JSON”的以下属性:parse、stringify、[Symbol.toStringTag]
问题描述
在我的 react-typescript 项目中,当我尝试将 aJSON
作为道具传递时遇到了打字错误。
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
对象类型。但是,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 , {}>
希望我说得通
推荐阅读
- sql - 在 SQL Server 中将单列数据排列在多列中
- github - 如何将 WSL-Ubuntu shell 添加到 Github 桌面 shell 列表?
- c# - 如何从 WPF 中的 ListView 选择中在 DataGrid 上添加数量列
- r - 如何创建自定义 x 轴刻度
- mongodb - MongoDB:卡住 mongod.lock 文件
- java - 有特殊要求的 Java 通行证生成器
- mysql - 如何像这样将 table1 重组和规范化为 table2?
- angular - (ionSelect) 不调用离子选择选项
- kde - 重访:如何启动具有多个选项卡的 KDE konsole 运行各种 progs?
- typescript - 这个 TypeScript 声明有什么问题?