Property id does not exist on type 'never'

Viewed 3364

I'm trying to do a .map function into a state array in Redux with Typescript, the problem is that it's throwing an error

[ts] Property 'id' does not exist on type 'never'

in the landing.id if statement, since its an array of objects the code makes sense for me but seems that I'm missing something there

export default function landingReducer (state = [], action) {
switch(action.type) {
  case ActionTypes.ADD_LANDING:
    return [...state, action.landing]
  case ActionTypes.EDIT_LANDING:
    return state.map(landing => {
      if (action.landing.id == landing.id) {
        return landing;
      }
    })

Thanks in advance!

2 Answers

It's probably due to types missing for the state and/or action arguments. Try this code that should work with TypeScript 2.4+, inspired by this article:

interface Landing {
    id: any;
}

enum ActionTypes {
    ADD_LANDING  = "ADD_LANDING",
    EDIT_LANDING = "EDIT_LANDING",
    OTHER_ACTION = "__any_other_action_type__"
}

interface AddLandingAction {
    type: ActionTypes.ADD_LANDING;
    landing: Landing;
}

interface EditLandingAction {
    type: ActionTypes.EDIT_LANDING;
    landing: Landing;
}

type LandingAction =
    | AddLandingAction
    | EditLandingAction;

function landingReducer(state: Landing[], action: LandingAction) {
    switch (action.type) {
        case ActionTypes.ADD_LANDING:
            return [...state, action.landing]

        case ActionTypes.EDIT_LANDING:
            return state.map(landing => {
                if (action.landing.id === landing.id) {
                    return landing;
                }
            });
    }
}

Your code is missing brackets and other necessary imports, which makes it difficult for someone else to quickly reproduce and diagnose.

That being said, TypeScript infers the state parameter as the type of an empty array literal [], which is considered to be never[], meaning it will always be empty. So the map function doesn't work because landing is being inferred as being an impossible value (there are no valid values of type never).

If you want to fix it, you should tell TypeScript what kind of array state is likely to be. The quick fix is to make it an array of any:

... function landingReducer (state: any[] = [], action) ...

Ideally, you should add more specific types to your parameters so that TypeScript can help you catch errors (how do you know that action has a type property?).

Hope that helps; good luck!

Related