3

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,
}

Darron Brown
  • 51
  • 1
  • 2
  • 4
  • 1
    See [similar issue](https://stackoverflow.com/questions/12789231/class-type-check-in-typescript#:~:text=TypeScript%20have%20a%20way%20of,type%20you%20think%20it%20is.) for typechecking during run time. – 98sean98 Dec 30 '20 at 05:33

1 Answers1

1

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, }

meowww
  • 138
  • 7