'Why is it possible to indirectly set inexistent properties on an object implementing an interface in Typescript?
I am a beginner in TypeScript. In my React project, I'm fetching some data and I'm setting the state to that data. It seems like the API is fetching an additional property: the independent property. However, if I try to set this property manually on an object implementing the Country interface, it fails with Type ... is not assignable to type 'Country'. Object literal may only specify known properties, and 'independent' does not exist in type 'Country' Also, if a property is not defined when manually setting the properties, it fails with missing property, however, if the response misses a specific property, there isn't any warning or error when setting the state (or when manually spreading the first element of the response in an object created with the Country interface). Do you think I'm messing up something in my code? If yes, what is a better way to set the state in the component? If not, what are the advantages of using the TypeScript interface/type here besides the property hints?
import { useEffect, useState } from 'react';
interface Country {
name: string;
population: Number;
region: string;
capital: string;
flags: {
svg: string;
png: string;
};
}
const CountryList: React.FC = () => {
const [countries, setCountries] = useState<Country[]>([]);
useEffect(() => {
const getCountries = async () => {
const countryAPIResponse = await (
await fetch(
'https://restcountries.com/v2/all?fields=name,population,region,capital,flags'
)
).json();
setCountries(countryAPIResponse);
};
getCountries();
}, []);
console.log(countries[0]);
return <div></div>;
};
export default CountryList;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
