Why is this code compiles successfully?

Topics: Code Checkins, General
Jul 15, 2013 at 5:08 PM
Edited Jul 15, 2013 at 5:10 PM
class Person {
    public firstName: string;
    
    constructor() {
    }
}

var person: Person;

person.firstName = "23";

alert(person.firstName);
(TypeScript 0.9)
We didn't create any object but this code actually compiles successfully. I'm pretty sure it shouldn't.
And of course we have a runtime error: "Unhandled Error: Cannot convert 'person' to object".
Jul 15, 2013 at 6:46 PM
It compiles because it's legal TypeScript code. TypeScript (as JavaScript) has no requirement that a variable is assigned before its used. This is, however, a form of static analysis which the compiler could do (and then provide warnings), and which they hopefully will add at some point.