简体   繁体   中英

“Property json does not exist on type {}” TypeScript

I am VERY new to TypeScript and have a project to finish up by tomorrow. What I am trying to do is import my json file onto componentDidMount() and render that on the app. I think I am at least doing something right since when I hover over 'response', I get all the different keys and values in my JSON file. I am having trouble rendering it on my App.

Here is the code(and don't mind searchField, I am adding that later and have no errors about it atm):

 import * as React from "react"; import GameCardList from "../GameCardList"; import logo from "./logo.svg"; export interface IGame { Name: string; ID: number; Slug: string; } interface IAppProps { } interface IAppState { games: Array<IGame>; searchfield: string; } export class App extends React.Component<IAppProps, IAppState> { constructor(props: Readonly<IAppProps>) { super(props); this.state = { games: [], searchfield: "" }; } componentDidMount() { import("../games.json").then( response => response.json()) //^^where the error is.then((users: any) => {this.setState({ games: users}); }); } onSearchChange = (event: { currentTarget: { value: any; }; }) => { this.setState({ searchfield: event.currentTarget.value }); } render() { const { games, searchfield } = this.state; const filteredGames = games.filter(game => { return game.Name.toLowerCase().includes(searchfield.toLowerCase()); }); return.games?length: <h1>Hello I am Loading;:</h1>: ( <div className="tc"> <GameCardList games={filteredGames} /> </div> ); } } // tslint:disable-next-line:no-default-export export default App;

What is interesting is that I had this EXACT same code in my other TS project with the JSON file and it is working fine. Hmm what am I doing wrong?

Also, on the topic of importing JSON in typescript file, any resources or other advice I can follow?

You don't need the .json() there, since your response is already the object that you need.

You can test that by printing the response: console.log(response)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM