Skip to content

Object possibly null in a callback function from a local variable defined inside a function #43827

Closed
@TheThing

Description

@TheThing

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

Playground link with relevant code

💻 Code

interface Item { name: string, finished: boolean }

let items: Array<Item> = []

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).

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions