Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
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;
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda