2

I'm trying to understand TypeScript better. I've found that if I write a bug like so:

function doStuff() {
    if (physician.email == "[email protected]")
    {
         var physician = {email: "[email protected]", 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.

1
  • 2
    Side note: this is one reason to avoid using var. It's a lot harder to accidentally cause bugs like this if you can't use the variable before declaring it. Commented Sep 25, 2018 at 0:11

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.