skip to Main Content

I have an state:

const [data, setData] = useState<{ [key in PROJECT_ROLE]?: number[] } | null>(null);

data is an object with some key in PROJECT_ROLE

This is PROJECT_ROLE:

export enum PROJECT_ROLE {
  OWNER = "OWNER",
  SUPERVISOR = "SUPERVISOR",
  QA = "QA",
  LAST_CHECK = "LAST_CHECK",
  CHECKER = "CHECKER",
  ENTRY = "ENTRY",
  MEMBER = "MEMBER",
}

I have an handle:

const handle = (index: number, role: PROJECT_ROLE) => {
  if (data && data[role]) {
    const id = data[role].indexOf(index);
  }
};

and I got:

enter image description here

Why? I checked it in if but it still show error.

And how can I fixed that?

2

Answers


  1. Type guarding property doesn’t change the type of the parent. There is an open GitHub issue ms/TS/42384 about it.

    Meanwhile, this can be fixed by the following approaches:

    If you disable strictNullChecks tsconfig option it there will be no error as shown in here

    An alternative solution would be to use optional chaining and store data[role] in a separate variable then check that variable in the if:

    const handle = (index: number, role: PROJECT_ROLE) => {
      const item = data?.[role]
      if (item) {
        const id = item.indexOf(index);
      }
    };
    

    playground

    Login or Signup to reply.
  2. You need to remove the ? operator in the state initialisation

      const [data, setData] = useState<{ [key in PROJECT_ROLE]: number[] } | null>(null);
    

    This will fix the TS error message

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search