Skip to content

Object is possibily undefined, but it's not #16889

Description

TypeScript Version: 2.4.1

Code

type cb = () => void;
function foo(cb?: cb) {
  const defaultFn = () => {};
  cb = cb || defaultFn;
  function bar() {
    cb(); // here I get the compiler error
  }
  bar();
}

Expected behavior:

The function foo should call second().

Actual behavior:

I get Object is possibily 'undefined' in that line where I left a comment.

I know it is not a good idea to reasign function arguments. Following code would work as expected:

type cb = () => void;
function foo(cb?: cb) {
  const defaultFn = () => {};
  const innerCb = cb || defaultFn; // don't override argument
  function bar() {
    innerCb()
  }
  bar();
}

But should the TypeScript compiler not be smart enough to recognize the closure? It only happens in the callback function onSomethingHappened. If I write it in the scope of the function foo it works as well. I only get the compiler error in the closure:

type cb = () => void;
function foo(cb?: cb) {
  const defaultFn = () => {};
  cb = cb || defaultFn;
  cb(); // no closure
}

PS: I know I could work with default arguments in the example above but my real production code is far more complex as this one 😉

Activity

  1. ikatyang commented on Jul 2, 2017

    @ikatyang
    Contributor
    type cb = () => void;
    
    function foo(cb?: cb) {
      const defaultFn = () => {};
      cb = cb || defaultFn;
    
      function bar() {
        cb(); // <-- should check if undefined first, error as expected
      }
    
      assignUndefinedToCb(); // <------ TS won't know what did you do to `cb`
    
      bar(); // 💥
    
      function assignUndefinedToCb() {
        cb = undefined;
      }
    }

    See #9998 for more details.

  2. screendriver commented on Jul 2, 2017

    @screendriver
    Author

    Big thank you! It seems that TypeScript is more intelligent than I 😂 👍👍

  3. locked and limited conversation to collaborators on Jun 14, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions