TypeScript Error:
Type '(location: Location) => Promise' is not assignable to type '(obj: Location) => void'. Types of parameters 'location' and 'obj' are incompatible. Type 'Location' is missing the following properties from type 'Location': state, city
Basically, user types in City and State, a little logic to parse the city and state, then the submitted user input gets raised from form component to top level App component, where there is an API get request. However 'fetchData' is throwing an error when I pass it down as a prop to weather-input (the form component). And 'obj', the argument for 'fetchData' is throwing an error in weather-input (the form component) at the bottom of 'handleSubmit' when it gets called. Not to mention onSumit inside the form tag (not shown below) is also throwing an error.
Question - what's the best way/flow/practice to make these proper 'types' and remove the errors?
weather-input.tsx file
import React, { FormEvent, useState } from 'react'; import { useHistory } from 'react-router-dom'; import '../styling/weather-input.css'; type WeatherInputProps = { fetchData: (obj: Location) => void; } export const WeatherInput: React.FC<WeatherInputProps> = ({fetchData}) => { const [input, setInput] = useState(''); const history = useHistory(); // FormEvent (event handle type), <HTMLButtonElement> restrict to specific element (generic) const handleSubmit = (e: FormEvent<HTMLButtonElement>): void => { e.preventDefault(); console.log(input) let words: string | string[] = input.replace(',', '') words = words.split(' ').reverse(); let obj = { state: words[0], city: words.slice(1).reverse().join(' ') } if (obj.state.length > 2 || obj.state.length < 2) { alert('use to letters for state') } else { fetchData(obj) } history.push('/forecast'); }App.tsx file
import React, { useState } from 'react'; import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import axios from 'axios'; import '../styling/App.css'; import { WeatherInput } from './weather-input'; import { Week } from './week'; import { Day } from './day'; type Location = { state: string; city: string; } const App: React.FC = () => { const [day, setDay] = useState<string[]>([]); const [items, setItems] = useState<string[]>([]); // openweathermap const fetchData = async (location: Location) => { const API_URL = 'https://api.openweathermap.org/data/2.5/forecast'; const API_KEY = process.env.REACT_APP_API_KEY; const options = `${API_URL}?q=${location.city},${location.state},US&appid=${API_KEY}` try { const {data} = await axios.get(options); setItems(data) } catch (err) { console.error(err) alert('Please check spelling of city and state.') }; }; const hanldeSingleDay = (e: any, day: any) => { let item: Array<string> = [day]; setDay(item) } return ( <Router> <div className="App"> <WeatherInput fetchData={fetchData}/>