Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

343
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda