Skip to content
webtype.orgwebtype.orgTS1107

    ↑↓ move · ⏎ open · esc close

    TS1107

    Jumping out of a callback

    Jump target cannot cross function boundary.

    The compiler’s own words. Not translated — this is the string you pasted into a search box.

    `break` and `continue` steer the loop they are written in. A callback is a different function, and that loop is not its to steer.

    Reproduction

    const ids = [1, 2, 3]
    const kept: number[] = []
    
    for (const id of ids) {
      ids.forEach(() => {
        if (id > 2) continue
      })
      kept.push(id)
    }

    The build asserts this emits exactly this code.

    Why the compiler says this

    `forEach` takes a function, and that function is called by `forEach` rather than by the loop. `continue` names a jump to the next iteration of an enclosing loop, and from inside the callback nothing encloses it but a call. The compiler rejects this while parsing, before it knows any types at all, because no arrangement of types would make the jump meaningful.

    Fixes

    1. 01
      const ids = [1, 2, 3]
      const kept: number[] = []
      
      for (const id of ids) {
        if (id > 2) continue
        kept.push(id)
      }

      Use a real loop. `for…of` gives `continue` something to jump to, and reads as the iteration it already was.

    2. 02
      const ids = [1, 2, 3]
      const kept = ids.filter((id) => id <= 2)

      Or stop steering and describe the result. Most `continue` inside a callback is a filter that has not been written as one.

    Takeaway

    Inside a callback the only way out is `return`. If you meant to skip or to stop, the array method that means "skip" or "stop" is usually the real answer.

    Errors