Object possibly null in a callback function from a local variable defined inside a function · Issue #43827 · microsoft/TypeScript (original) (raw)

Bug Report

🔎 Search Terms

Object possibly null callback
Object possibly null function local

🕗 Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about functions and variables.

Playground link with relevant code

💻 Code

interface Item { name: string, finished: boolean }

let items: Array = []

function asyncFakeSend(cb: Function) { setTimeout(cb, 100) }

function getLatestAndSend() { let found: Item | null = null

for (let i = 0; i < items.length; i++) { if (!items[i].finished) { found = items[i] break } }

if (!found) return

asyncFakeSend(() => { found.finished = true getLatestAndSend() }) }

🙁 Actual behavior

Typescript thinks found variable inside the asyncFakeSend could be null even though I've already verified it is not with the above if statement and there is no possible way of re-assigning that variable in the function after the fact or at least in the above code sample.

🙂 Expected behavior

No errors.

🙁 Workaround

My coworker suggested I create a new variable from the found inside the function like so:

function getLatestAndSend() {
  let found: Item | null = null

  for (let i = 0; i < items.length; i++) {
    if (!items[i].finished) {
      found = items[i]
      break
    }
  }

  if (!found) return

  let foundToMakeTypeScriptHappy = found

  asyncFakeSend(() => {
    foundToMakeTypeScriptHappy .finished = true
    getLatestAndSend()
  })
}

But I've never been a fan of adding code noise that provides no functionality and only exists to make typescript happy. Especially when in above situation, found.finished can never be null (as far as I understood javascript).