Evan
Evan

Reputation: 61

return full class with reducer statement

I'm getting the error:

"Type '{ permissions: any; avatarUrl: string; email: string; calendarStatus: string; roleID: number; lastLoginDate: DateType; mfa: boolean; availability: string | null; outOfOffice: any[]; ... 4 more ...; name: string; }' is missing the following properties from type 'User': role, subtitle, searchField, link, and 3 more.ts(2740)"

with the following function:

const reducer = (state: User, action: { type: string, value: any | object }): User => {
  switch (action.type) {
    case 'roleChange':
      return { ...state, ...action.value }
    case 'permissionsChange':
      return { ...state, permissions: { ...state.permissions, ...action.value } }
    default:
      break
  }
  return state
}

The problem is with this line:

return { ...state, permissions: { ...state.permissions, ...action.value } }

My intention is return the full class, not a partial. I'm aware I can type it to return a Partial User, but this fix makes other parts of my code not workable, as I reference certain attributes on the User class.

Upvotes: 0

Views: 39

Answers (1)

Wolfgang
Wolfgang

Reputation: 1388

You're spreading the action.value instead of assigning a value to a property. Should look like this.

const reducer = (state: User, action: { type: string, value: any | object }): User => {
  switch (action.type) {
    case 'roleChange':
      return { ...state, ...action.value }
    case 'permissionsChange':
      return { ...state, permissions: action.value }
    default:
      break
  }
  return state
}

Or if you know the field inside permissions you want to update

const reducer = (state: User, action: { type: string, value: any | object }): User => {
  switch (action.type) {
    case 'roleChange':
      return { ...state, ...action.value }
    case 'permissionsChange':
      return { ...state, permissions: { ...state.permissions, someField: action.value } }
    default:
      break
  }
  return state
}

Upvotes: 0

Related Questions