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

345
Visualizações
Property 'error' does not exist on type '{} | user | error'
  type user = {
    id: number,
    token: string
  }

  type errorObject = {
    error: string
  }

  interface authState {
      user: user | {} | errorObject,
  }

  const initialState: authState = {
      user: {}
  }

  const error : errorObject = {"error": "hi"}

  initialState.user = error

  console.log(initialState.user.error) // Property 'error' does not exist on type '{} | user | error'.

Why does this error? It has an error property so why does it say it doesn't exist? I'm confused.

My goal was to make the user object to be any of these types:

user = {} 
// or
user = {"id": number, "token": "1234"}
// or
user = {"error": "error"}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your type is pretty broad, the compiler is throwing an error becuase the property may not be present in the paramter.

If you are certain that in a given circumstances the error property would exist, you can use a type assertion.

Ex. (initialState.user as errorObject).error

Or if you are not certain of that, you could create your own user defined type guard, for instance:

function instanceOfErrorObject(data: user | {} | errorObject): data is errorObject {
    return data.hasOwnProperty("error");
}

if you call this function before trying to access error property, compiler will know that it's of an appropriate type:

const user = initialState.user;
if (instanceOfErrorObject(user)) console.log(user.error);
about 4 years ago · Juan Pablo Isaza Relatório
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