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:
Why? I checked it in if
but it still show error
.
And how can I fixed that?
2
Answers
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 hereAn alternative solution would be to use optional chaining and store
data[role]
in a separate variable then check that variable in theif
:playground
You need to remove the ? operator in the state initialisation
This will fix the TS error message