Properties in the module

Is there a way to define a property in a TypeScript module ?

None of these compilations:

 module My { // doesnt work get Value(): number { return 42; } // doesn't work either get function Value(): number { return 42; } // nope function get Value(): number { return 42; } } 

Now I have to use this:

 module My { declare var Value: number; Object.defineProperty(My, "Value", { get: () => 42 }); } 

The second form seems messy to me, and the code hint doesn't really see it as a read-only property, but as just a variable.

Is there a standard way to define properties directly inside modules?

+3
source share
3 answers

No, there is no way to declare a property on a module in TypeScript using any of the features of the document language.

You can do this in several rounding methods.

A module can extend existing class or function . So, I created a class with the static property, and then created a module that uses the same name as the class .

 class My { static get Value():Number { return 42; } } module My { var works: boolean = true; } alert(My.Value); 

It generates one weirdness in the generated JavaScript code that you wouldn’t do manually (and in any case it needs to be removed by most optimizers) ... when creating the module, it will update the My variable. This does not cause a run-time problem since the variable has already been stripped in JavaScript and will not conflict with the first use.

Here is another option:

 module Global { class Inner { get Value():Number { return 42; } } export var My; My = new Inner(); } var My = Global.My; alert(My.Value); 

While it represents an extra namespace, you can manipulate it, but you want to use the inner class or change it as needed. Thus, the variable My is global, as it would be like module .

+3
source

Instead of using the module keyword, use export instead, which allows you to do what you want to do by treating the file itself as a module (how CommonJS and AMD work).

 // in My.ts var My = { get value() { return 42; } }; export = My; 


 // in foo.ts import My = require('My'); console.log(My.value); 

I describe this in more detail in a blog post, The Ultimate TypeScript Guide .

+1
source

I tried singleton

 let My = { get value() { return 42; } } export My 

but ran into a problem when the emitted JS still said get value() and didn't work in older versions of Node. I tried Object.defineProperty , but then lost TypeScript compatibility. Here is my bridge that captures both cases:

 interface My { value: number } // type assertion fixes TypeScript usage let my = <My>{} // defineProperty fixes JS usage Object.defineProperty(my, 'value', { get: () => 42 }); export = my; 

It is used as a module in typescript.

 import * as my from './my' my.property // returns 42 // my.property = doesn't work 
0
source

Source: https://habr.com/ru/post/1214575/


All Articles