Q:

TypeScript doesn't catch undefined variable?

I'm trying to understand TypeScript better. I've found that if I write a bug like so:
function doStuff() {
    if (physician.email == "george@gmail.com")
    {
         var physician = {email: "bob@gmail.com", name: "Dr. Bob"};
         /* .... */
    } }

TypeScript will NOT catch the problem that the physician object is defined AFTER we attempted to use one of its properties. This results in a run-time error of: 

Type error: Cannot read property 'email' of undefined.

Why doesn't the TypeScript transpiler catch stuff like this? Using TypeScript 2.0 I believe.

A:

In JavaScript, declarations (though not initializations) of var variables are implicitly moved to the beginning of the containing function, and var variables are implicitly initialized to undefined until the user-written initializer is reached.  By default, TypeScript takes the position that reading the implicit undefined value is legitimate.  One way you can make it an error is to enable the strictNullChecks compiler option (or the umbrella strict option) and give the variable a type that does not include undefined (which happens automatically by inference in your example).  Here's the documentation for that feature.  tslint also has a no-use-before-declare rule that should detect the problem.
In contrast to var variables, using a let or const variable before its declaration is always a compile error in TypeScript.  This is one of the reasons that let (or const) is highly recommended over var.  Use of a let variable after it is declared (and implicitly initialized to undefined) but before it is initialized by user code follows the same rules as var.

