I'm banging my head over this and don't get it. 'rules.optional' possibly undefined even after checking it's not. Check works normally (so case1 and case 2 are clear), but not inside array.find() which is case 3 below. I understand why it doesn't work in case 4, as it is executed asynchronously and can change in the meantime, but case 3?
const rules: {
name: string,
optional?: { max: number, name: string }
} = { name: "test" }
const arr: string[] = ["a", "b", "c"]
// case 1
const obvious = rules.optional.max //rules.optional possibly undefined
// case 2
if (rules.optional) {
const ok = rules.optional.max //OK, as expected
}
// case 3
if (rules.optional) {
const error = arr.map(elem => elem === rules.optional.name) //rules.optional possibly undefined !?
}
// case 4
if (rules.optional) {
setTimeout(() => { console.log(rules.optional.name) }, 1000)
}
Note that those are simplified extracts from my code. In real code, I cannot use ! (eslint complains) nor ? (code complains)
const ro = rules.optionaland use it inside .map() then TS picks it up. I'm still confused why this is necessary. It doesn't seem it is a very complex logic in the example above.