I'm new to TypeScript but have a background in C# and I'm a little bit confused about how to handle TypeScript modules. I've been thinking about modules as namespaces in C# but maybe this is wrong because my code doesn't behave the way I was expecting.
I have the following folder structure:
|-myApp
| |-myController
| | |-myController.ts
| |-models
|-a.ts
|-b.ts
and this code:
// a.ts
module MyApp.Models {
export class A {
}
}
// b.ts
module MyApp.Models {
export class B {
}
}
// myController.ts (THIS DOESN'T WORK)
module MyApp.MyController {
import Models = MyApp.Models;
class MyController {
a = new Models.A();
b = new Models.B();
}
}
// myController.ts (THIS WORKS)
module MyApp.MyController {
class MyController {
a = new Models.A();
b = new Models.B();
}
}
In the example above my attempt at importing the module (namespace?) Models will result in an error at runtime because Models is undefined. However if I remove the import-statement the code will works just fine. I'm probably not thinking clearly and doing some really stupid beginners mistake but could someone please tell me what I'm doing wrong and what the best way to use modules in my particular scenario would be. Why does it work if I remove the import but not with it?
Regards Kristofer
Sorry for late answer.
Problem and magic around modules/namespaces are occurred in three things:
Your system - due to your system TypeScript compiler discover files by difference ways, and when it compile your source code to JS code it take a place, because the same ts files provide different results JS.
Understanding magic statement /// <reference path="***"/>. It is very important use this word if there are no additional Module System like AMD, or System.js, etc. Because if you use merged compilation it take place, because it tell compiler in what order it should compile files.
Understanding of JS execution and structure that TypeScript propose in compiled JS file. Just consider next example - (it is your compiled into JS example)
var MyApp;
(//functon wrapping
function (MyApp) {//function declaration
var MyController;
(function (MyController_1) {
var Models = MyApp.Models;
var MyController = (function () {
function MyController() {
this.a = new Models.A();
this.b = new Models.B();
}
return MyController;
})();
MyController_1.MyController = MyController;
})(MyController = MyApp.MyController || (MyApp.MyController = {}));
}
)(MyApp || (MyApp = {}));// end of function wrapping and it execution
/// <reference path="myApp/MyController/myController.ts"/>
new MyApp.MyController.MyController(); // createing new instance of MyController
var MyApp;
(function (MyApp) {
var Models;
(function (Models) {
var B = (function () {
function B() {
}
return B;
})();
Models.B = B;
})(Models = MyApp.Models || (MyApp.Models = {}));
})(MyApp || (MyApp = {}));
var MyApp;
(function (MyApp) {
var Models;
(function (Models) {
var A = (function () {
function A() {
}
return A;
})();
Models.A = A;
})(Models = MyApp.Models || (MyApp.Models = {}));
})(MyApp || (MyApp = {}));
//# sourceMappingURL=app.js.map
if you dive deeper into JS you would find that the JS code is executing in the next order
Reading function and passing it into the memory
Executing another code
That is why the next code would work
myFunction();
function myFunctuion(){};
Due to typescript JS building technics for modules and classes it use anonimous function like this:
var MyApp;
(//functon wrapping
function (MyApp) {//function declaration
var MyController;
(function (MyController_1) {
var Models = MyApp.Models;
var MyController = (function () {
function MyController() {
this.a = new Models.A();
this.b = new Models.B();
}
return MyController;
})();
MyController_1.MyController = MyController;
})(MyController = MyApp.MyController || (MyApp.MyController = {}));
In this case calling like next cause runtime exception, because anonimus block has not executed before.
MyController(); // here runtime exception
var MyController = (function () {
function MyController() {
this.a = new Models.A();
this.b = new Models.B();
}
return MyController;
})();
Now, back to the our example and discover it, as you see MyController defined earlier, than we do execution of anonymous function and variable with name MyController now exist in the global scope.
The next step is executing constructor of MyController class, in it we find next two part of code
this.a = new Models.A();
this.b = new Models.B();
But here we get an error because the anonymous function that consist variable Modules and classes A and B has not executed yet. That is why, in this moment we getting the error that variable Modules is undefined.
I hope that this topic make your knowledge about JS and TS better, and help you in your new features!!!
Good Luck!
P.S. Here is working example
Typescript modules are similar to C# namespaces. They help organize the codebase.
The import statement can be used for two things: to provide an alias or to import external modules.
To create an alias you use the import as you did:
import Models = App.Models;
To import an external module you use:
import Models = './path/to/module';
I can't figure out why your code doesn't work. I tried to reproduce it on my machine but both controllers work for me.
Related
I have a class in c++ that I'm wrapping into python with pybind11. That class has a std::function, and I'd like to control how the arguments to that function are dealt with (like return value policies). I just can't find the syntax or examples to do this...
class N {
public:
using CallbackType = std::function<void(const OtherClass*)>;
N(CallbackType callback): callback(callback) { }
CallbackType callback;
void doit() {
OtherClass * o = new OtherClass();
callback(o);
}
}
wrapped with
py::class_<OtherClass>(...standard stuff...);
py::class_<N>(m, "N")
.def(py::init<N::CallbackType>(),
py::arg("callback"));
I all works: I can do this in python:
def callback(o):
dosomethingwith(o)
k = N(callback)
, but I'd like to be able to control what happens when callback(o); is called - whether python then will take ownership of the wrapped o variable or not, basically.
I put a printout in the destructor of OtherClass, and as far as I can tell, it never gets called.
OK, I think I figured it out:
Instead of std::function, use a pybind11::function:
using CallbackType = pybind11::function
and then
void doit(const OtherClass &input) {
if (<I want to copy it>) {
callback(pybind11::cast(input, pybind11::return_value_policy::copy));
} else {
callback(pybind11::cast(input, pybind11::return_value_policy::reference));
}
}
I see nothing in pybind11/functional that allows you to change the ownership of the parameters at the point of call, as the struct func_wrapper used is function local, so can not be specialized. You could provide another wrapper yourself, but in the code you can't know whether the callback is a Python function or a bound C++ function (well, technically you can if that bound C++ function is bound by pybind11, but you can't know in general). If the function is C++, then changing Python ownership in the wrapper would be the wrong thing to do, as the temporary proxy may destroy the object even as its payload is stored by the C++ callback.
Do you have control over the implementation of class N? The reason is that by using std::shared_ptr all your ownership problems will automagically evaporate, regardless of whether the callback function is C++ or Python and whether it stores the argument or not. Would work like so, expanding on your example above:
#include <pybind11/pybind11.h>
#include <pybind11/functional.h>
namespace py = pybind11;
class OtherClass {};
class N {
public:
using CallbackType = std::function<void(const std::shared_ptr<OtherClass>&)>;
N(CallbackType callback): callback(callback) { }
CallbackType callback;
void doit() {
auto o = std::make_shared<OtherClass>();
callback(o);
}
};
PYBIND11_MODULE(example, m) {
py::class_<OtherClass, std::shared_ptr<OtherClass>>(m, "OtherClass");
py::class_<N>(m, "N")
.def(py::init<N::CallbackType>(), py::arg("callback"))
.def("doit", &N::doit);
}
For the following JavaScript code, how can I write it in ReasonML?
class HelloWorld extends HTMLElement {
constructor() {
super();
// Attach a shadow root to the element.
let shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.innerHTML = `<p>hello world</p>`;
}
}
I could not find any documentation on writing classes in ReasonML? I cannot use plain objects/types as I need to extend from HTMLElement class which doesn't work with ES style classes.
I have looked into this existing question - How to extend JS class in ReasonML however, it is a different thing. To write web component, we need to extend HTMLElement and must call it with new keyword. ES5 style extension mechanism doesn't work.
You can't. Not directly at least, since BuckleScript (which Reason uses to compile to JavaScript) targets ES5 and therefore has no knowledge of ES6 classes.
Fortunately, ES6-classes require no special runtime support, but are implemented as just syntax sugar, which is why you can transpile ES6 to ES5 as shown in the question you link to. All you really have to do then, is to convert this transpiled output into ReasonML:
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var BaseElement = (function (_super) {
__extends(BaseElement, _super);
function BaseElement() {
_super.call(this);
}
return BaseElement;
}(HTMLElement));
And depending on what specific class-features you actually need, you can probably simplify it a bit.
I'm using IntelliJ IDEA's File Watcher to automatically compile the TypeScript files, but for some reason it's not liking classes defined within blocks / function closures:
Is there a way around this without having to move everything to the top-level / global scope?
Using the following code in TypeScript results in practically the same JavaScript that you appear to be aiming for...
namespace MY_NAMESPACE {
export class AssetService {
}
}
Resulting code:
var MY_NAMESPACE;
(function (MY_NAMESPACE) {
var AssetService = (function () {
function AssetService() {
}
return AssetService;
}());
MY_NAMESPACE.AssetService = AssetService;
})(MY_NAMESPACE || (MY_NAMESPACE = {}));
If you want to really reduce the scope, switch to external modules (AKA "modules" these days).
If you don't export the class from the module/file, it won't be visible globally, i.e. there's no reason to enclose class definitions in function scopes.
More about modules in TS: https://www.typescriptlang.org/docs/handbook/modules.html
Trying to use ES6 classes in WebStorm 8/9 and getting this error when I add a getter:
'use strict';
(function () {
class Collection {
constructor(resource) {
this._models = [];
this._resource = resource;
}
fetch() {
this._models = this._resource.query();
}
get models() {
return this._models;
}
}
})();
Moving the class definition outside the anonymous function removes the error, but this isn't an option.
I disabled all inspections and intentions in the preferences. Any ideas how to remove/suppress this message?
WEB-13447 is fixed in webStorm 10. Please try WebStorm 10 RC
Can someone explain why the following typescript code compiles? It seems to me that it could never successfully run.
class Xyz
{
static x : Abc = new Abc();
}
class Abc
{
}
There is no compile-time error, since it is equivalent to this syntactically valid JavaScript
var Xyz = (function () {
function Xyz() {
}
Xyz.x = new Abc();
return Xyz;
})();
var Abc = (function () {
function Abc() {
}
return Abc;
})();
but it will have a runtime error since you try to instantiate a member of Abc before Abc is defined.
TypeScript doesn't do any enforcement of ordering of constructs in your code. Consider some slight variant that would be valid -- it's not immediately obvious what things should be allowed or disallowed in terms of ordering.
class Xyz
{
static x = () => new Abc();
}
class Abc
{
}
There's an issue tracking adding this as an option for the straightforward cases.