Skip to content

StrictNullChecks and throw/return with incorrect when used with closure scope #13572

@tlong-dev

Description

@tlong-dev

TypeScript Version: 2.1.5

Code

function other() {
  return new Promise((resolve, reject) => {
    resolve("OK!");
  });
}

function test(hosts: {whatever: boolean}[]) {
  let host = hosts.filter((f) => f.whatever).shift();

  if (!host) {
    throw new Error("Crap!");
  }

  return other().then(() => {
    console.log(`${host.whatever} selected`);
  });
}

Playground

Expected behavior:

Do not emit an error about host possibly being null, since the method exits early if that's the case.

Actual behavior:

Typically when using strictnullchecks Typescript is intelligent enough to understand that when you throw an error from a method based on a type check/guard it narrows the type after the statement. As indicated in this short example:

function test(hosts: {whatever: boolean}[]) {
  let host = hosts.filter((f) => f.whatever).shift();

  // Correctly calls out hose as possibly being null
  console.log(`${host.whatever} selected`);
  
  if (!host) {
    throw new Error("Crap!");
  }

  // Does not complain here because of the above check/throw
  console.log(`${host.whatever} selected`);
}

For some reason when you add the return of the function and use host through a closure it starts complaining.

I'm sure it's the closure, but I don't see how this could error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions