Bas
Bas

Reputation: 1433

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

Upvotes: 0

Views: 479

Answers (1)

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6714

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);

Upvotes: 1

Related Questions