Understanding Let and Arrow Functions
class Test {
constructor() {
}
hello() : string {
return "Hello";
}
}
declare let g : object;
if (g instanceof Test) {
() => {
g.hello(); // error
};
}
g
is a Test
at function definition, but its type may change when the function is executed.
Using Const with Arrow Functions
class Test {
constructor() {
}
hello() : string {
return "Hello";
}
}
declare const g : object;
if (g instanceof Test) {
() => {
g.hello(); // ok
};
}
g
is constant, and its type remains consistent as a Test
after function definition.
Const with Regular Function
class Test {
constructor() {
}
hello() : string {
return "Hello";
}
}
declare const g : object;
if (g instanceof Test) {
function f() {
g.hello(); // error
};
}
In the underlying implementation, the regular function f
is defined with ES5 var
instead of ES6 let
. This can lead to variable hoisting and issues when g
is not a Test
.