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 😉
TypeScript Version: 2.4.1
Code
Expected behavior:
The function
fooshould callsecond().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:
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 functionfooit works as well. I only get the compiler error in the 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 😉