Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a variable with get/set inside a module in Typescript

Tags:

typescript

I want to create a variable with get/set properties inside a module. I saw some working examples for creating a get/set property inside a class that looks like this :

class MyClass {
    private view;
    get View() { return this.view; }
    set View(value) { this.view = value }
}

But I want to do the same inside a module :

module MyModule {
    export var view;
    //I want to create get/set methods for view property here
}

How do I do that ?

like image 849
FacePalm Avatar asked Mar 14 '13 15:03

FacePalm


People also ask

How do you use GET method in TypeScript?

The get method can be defined in a program to extract the value of any variable or to access the property of any object in TypeScript. The get keyword is used in the program along with the name of the method within which the code to be executed on the object. methodname() is written.

How do you declare a variable inside a function in TypeScript?

The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable. Declare its type and value in one statement.

How do I create a global variable in TypeScript?

To declare a global variable in TypeScript, create a . d. ts file and use declare global{} to extend the global object with typings for the necessary properties or methods.

What is the scope all the variables declared in a TypeScript module?

It executes in the local scope, not in the global scope. In other words, the variables, functions, classes, and interfaces declared in a module cannot be accessible outside the module directly. We can create a module by using the export keyword and can use in other modules by using the import keyword.


1 Answers

I think it's just an oversight; I'll raise this with the design team (I don't see any obvious reason why it would be disallowed other than "we haven't implemented it yet"). It's fairly straightforward to work around lack of first-class language support for it:

module Bar {
    var _qua = 42;

    declare export var qua: number;
    Object.defineProperty(Bar, 'qua', {
        get: function() { return _qua; },
        set: function(value) { _qua = value; }
    }); 
}

// Works
var x = Bar.qua;
console.log(x);
Bar.qua = 19;
console.log(Bar.qua);
like image 199
Ryan Cavanaugh Avatar answered Oct 02 '22 13:10

Ryan Cavanaugh