How to verify Interface with Axios GET response using TypeScript

Viewed 399

Data is coming back successfully from the API. This is my first time calling an API using TypeScript. The problem I am having is that I am not sure if my interface successfully verifies the API data or not.

const App = () => {
  const [userData, setUserData] = useState<User[]>([])
  console.log('User data: ', userData);

  useEffect(() => {
    axios
      .get<User[]>('https://jsonplaceholder.typicode.com/users')
      .then((response) => {
        setUserData(response.data)
      })
      .catch(error => console.log(error.message))
  }, [])

  return ...
};

export default App;

Here is my interface

export interface User {
  id: number,
  name: string,
  username: string,
  email: string,
  address: Address,
  phone: string,
  website: string,
  company: Company,
}

export interface Address {
  street: string,
  suite: string,
  city: string,
  zipcode: string,
  geo: Geolocation,
}

export interface Geolocation {
  lat: string,
  lng: string,
}

export interface Company {
  name: string,
  catchPhrase: string,
  bs: string,
}

1 Answers

If you not sure about your props in interface has data or not. You could use this syntax interface your_interface_name { your_props_name?: type_data }

ex: export interface Geolocation { lat?: string, lng?: string, }

Related