Stuart Blackler
Stuart Blackler

Reputation: 3772

Unable to setup property in constructor

Given the following Typescript:

class Tester{
    constructor(data){      
        this.Data = data;
    }
}

which generates the following Javascript:

var Tester = (function () {
    function Tester(data) {
        this.Data = data;
    }
    return Tester;
})();

Are there any reasons why the Typescript is invalid when the resulting Javascript appears to be valid (and works)?

JS Output

Typescript Playground Version

Upvotes: 0

Views: 57

Answers (1)

billy
billy

Reputation: 1160

Add your "Data" member to your class :

class Tester {
    public Data: string;

    constructor(data) {
        this.Data = data;
    }

}

UPDATE

There is a shorter way to define class members :

class Tester {
    constructor(private data: string) {
         // this constructor signature defines a private member for the class 
         // and initializes it upon the constructor being called with a parameter.
    }

    getData(): string {
         return this.data;
    }
}

http://www.typescriptlang.org/Playground/#src=%0A%0Aclass%20Tester%7B%0A%09%0A%09constructor%28data%29%7B%0A%09%09%0A%09%09this.Data%20%3D%20data%3B%0A%09%7D%0A%09%0A%7D

Upvotes: 1

Related Questions