Typescript: 'Cannot find name' error of imported class - module

I have a file a.ts which contains a class A inside a module:
module moduleA {
export class A {
}
}
export = moduleA.A;
And another file b.ts which imports class A:
import A = require('a.ts');
class B {
// This leads to an error: Cannot find name 'A'
private test: A = null;
constructor() {
// But this is possible
var xyz = new A();
}
}
Interestingly, Typescript shows an error when I want to use A as a type in B. However, instantiating A does not lead to an error.
Can anybody explain me, why this is like that?
Thank you very much!

The use of the namespace module moduleA is not necessary... you can do this...
the keyword module is synonymous with namespace (C#) now... best practice is to use the ES6 style module structure which is basically each file is a module and export what you need and import what you need from elsewhere.
// a.ts
export class A {}
// b.ts
import { A } from './a';
class B {
private test: A = null; // will not error now
constructor () {
var xyz = new A();
}
}
Note: this is based upon TypeScript v1.5+

Related

Specialized Singleton implementation

I am looking for specialized singleton implementation, probably I might be using wrong terminology and hence looking for expert suggestion. Here is my scenario:
There is common code which can be called by ComponentA or ComponentB. I need to push telemetry data from the common code. Telemetry needs to have information that whether this common code get called by ComponentA or ComponentB.
So common code will have just this line of code:
telemetry.pushData(this._area, data);
where this._area tells the telemetry data is getting pushed for which component
I need to push telemetry data from multiple places so it would be good if object got created once and used through out the code lifetime
One option I can think of passing component context to the common code which in mind doesn't look right, hence looking for suggestion what kind of pattern one should use in this case?
This is what I am thinking
// Telemetry.ts file present in shared code
export class Telemetry extends Singleton {
public constructor() {
super();
}
public static instance(): Telemetry {
return super.instance<Telemetry>(Telemetry);
}
public publishEvent(data): void {
if (!this.area) {
throw new Error("Error: Initialize telemetry class with right area");
}
pushtelemetryData(this.area, data);
}
public area: string;
}
// Create Telemetry object from component A
Telemetry.instance().area = "ComponentA";
// Shared code will call telemetry publishEvent
Telemetry.instance().publishEvent(data);
Thanks
It's not a good pattern to use in TypeScript where you would generally inject dependencies.
If you must absolutely do it then you can do it by faking it somewhat:
namespace Telemetry {
var instance : SingletonSomething;
export function push(data: Any) : void {
if (instance == null) {
instance = new SingletonSomething();
}
instance.push(data);
}
class SingletonSomething() { ... }
}
and then you could call
Telemetry.push(data);
You can imitate the singleton pattern in typescript easily:
class Telemetry {
private static instance: Telemetry;
public static getInstance(): Telemetry {
if (Telemetry.instance == null) {
Telemetry.instance = new Telemetry();
}
return Telemetry.instance;
}
...
}
If you have your code in some sort of closure (module, namespace, etc) then you can replace the static member with:
let telemetryInstance: Telemetry;
export class Telemetry {
public static getInstance(): Telemetry {
if (telemetryInstance == null) {
telemetryInstance = new Telemetry();
}
return telemetryInstance;
}
...
}
But then you can also replace the static method with:
let telemetryInstance: Telemetry;
export function getTelemetryInstance(): Telemetry {
if (telemetryInstance == null) {
telemetryInstance = new Telemetry();
}
return telemetryInstance;
}
export class Telemetry {
...
}
At this point, in case you are using some sort of closure, you might ask yourself if you really need the class at all?
If you use this as a module:
// telemetry.ts
export interface TelemetryData {
...
}
export function pushData(data: TelemetryData): void {
...
}
Then you get exactly what you're looking for, and this is more of the "javascript way" of doing it.
Edit
In the telemetry module there's no need to know the users of it.
If the Telemetry.pushData function needs to have information about the object that called it then define an interface for it:
// telemetry.ts
export interface TelemetryData {
...
}
export interface TelemetryComponent {
name: string;
...
}
export function pushData(data: TelemetryData, component: TelemetryComponent): void {
...
}
Then in the other modules, where you use it:
// someModule.ts
import * as Telemetry from "./telemetry";
class MyComponent implement Telemetry.TelemetryComponent {
// can also be a simple string property
public get name() {
return "MyComponent";
}
fn() {
...
Telemetry.pushData({ ... }, this);
}
}
2nd Edit
Because you are using a module system, your module files are enough to make singletons, there's no need for a class to achieve that.
You can do this:
// telemetry.ts
let area: string;
export interface TelemetryData {
...
}
export function setArea(usedArea: string) {
area = usedArea;
}
export function pushData(data: TelemetryData): void {
...
}
Then:
Telemetry.setArea("ComponentA");
...
Telemetry.publishEvent(data);
The telemetry module will be created only once per page, so you can treat the entire module as a singleton.
Export only the functions that are needed.

Default imports with TypeScript

Using tsc 1.8.9... why are these imports not working? I thought TypeScript implemented ES6 module syntax?
"classes/person.ts"
export default class Person {
protected _name: string;
protected _language: string;
constructor(name: string) {
this._name = name;
this.hello();
}
public hello() {
console.log("Hello, " + this._name);
console.log("Lang: " + this._language);
}
}
"classes/englishman.ts"
import Person from "person"
export default class Englishman extends Person {
constructor(name: string){
this._language = "en_GB";
super(name);
}
}
"main.ts"
import * as $ from "jquery";
import Englishman from "classes/englishman";
let tom: Person = new Englishman("Tom");
console.log(tom);
$("body").html(`<h1>TEST</h1>`);
Errors:
source/main.ts(2,24): error TS2307: Cannot find module
'classes/englishman'. source/main.ts(4,10): error TS2304: Cannot find
name 'Person'. [13:53:43]
TypeScript: 2 semantic errors
After some changes, it worked for me, tested in ES5 and ES6. I hope to help you:
Original
import Person from "classes/person";
import Englishman from "classes/englishman";
Change for test
import Person from './person';
import Englishman from './classes/englishman';
maybe you need to check your directory tree.
Add
import Person from './classes/person';
.
import Person from './person'; //<-- change
export default class Englishman extends Person {
constructor(name: string){
this._language = "en_GB";
super(name);
}
}
export default class Person {
protected _name: string;
protected _language: string;
constructor(name: string) {
this._name = name;
this.hello();
}
public hello() {
console.log("Hello, " + this._name);
console.log("Lang: " + this._language);
}
}
import Englishman from './classes/englishman'; //<-- change
import Person from './classes/person'; //<-- add
class HelloWorld{
public static main(){
let tom: Person = new Englishman("Tom");
console.log(tom);
}
}
HelloWorld.main();
Hello, Tom
Lang: en_GB
Englishman { _language: 'en_GB', _name: 'Tom' }
tsc Version 1.8.2
node v5.4.1
Make sure you are compiling with ES6 target, if I'm not mistaken, ES5 is still the default target.

Why does Luxe/Flow quit unexpectedly after building with my PhysicsHandler class?

My PhysicsHandler class seems to be causing Luxe to quit unexpectedly, and I have no idea why.
Everything runs fine until I declare a class-variable, at which point it crashes a couple of seconds after loading. What's weird is that I have another class (InputHandler) that declares class-variables and runs fine. Not sure whether this is a problem with my code (somehow... ), Luxe, or Flow.
Main class:
import luxe.Input;
import luxe.Parcel;
import luxe.ParcelProgress;
import InputHandler;
import PhysicsHandler;
import Player;
enum GAME_STATE
{
play;
pause;
}
class Main extends luxe.Game {
var INPUT_HANDLER: InputHandler;
override function ready() {
var assetsParcel = new Parcel
({
textures:
[
{ id:"assets/block.png" },
{ id:"assets/background.png" }
]
});
new ParcelProgress
({
parcel : assetsParcel,
oncomplete : onAssetsLoaded
});
assetsParcel.load();
INPUT_HANDLER = new InputHandler();
INPUT_HANDLER.GameState = GAME_STATE.play;
}
private function onAssetsLoaded(_)
{
var player = new Player();
INPUT_HANDLER.setPlayerEntity(player);
}
override function update(dt:Float) {
INPUT_HANDLER.update();
}
}
InputHandler class:
import luxe.Input;
import luxe.Entity;
import Main;
class InputHandler
{
public var GameState: EnumValue;
private var player: Entity;
// functions, etc. below here...
}
PhysicsHandler class (the troublemaker... ):
import Main;
class PhysicsHandler
{
public var GameState: EnumValue;
}
This is all it takes to crash the game somehow. As you can see, I'm not even instantiating the PhysicsHandler class yet, just importing it.
Okay, so I was able to sort this with some help on the Snowkit forums. Apparently, Luxe doesn't play well with the latest version of hxcpp, so downgrading to 3.2.102 worked. Result.

Can typescript external modules have circular dependencies?

It looks like this is not allowed. requireJS is throwing an error on the following (this post is different as it was resolved with internal modules):
element.ts:
import runProperties = require('./run-properties');
export class Element {
public static factory (element : IElement) : Element {
switch (element.type) {
case TYPE.RUN_PROPERTIES :
return new runProperties.RunProperties().deserialize(<runProperties.IRunProperties>element);
}
return null;
}
}
run-properties.ts:
import element = require('./element');
export class RunProperties extends element.Element implements IRunProperties {
}
No, modules can't have circular dependencies unless they are in the same file. Each file is being processed in sequence, synchronously, so the full file definition (including all of the exports for example) hasn't been completed when it goes to second file, which immediately tries to require/reference the first file, and so on.
Normally, you can break a circular dependency by introducing an interface or base class into a common definition file(s) (basically interfaces only) and having the other files use that as a common "interface" rather than directly referencing the classes. This is a typical pattern in many platforms.
I have same issue, I was able to fix it by creating factory class that allows registration of child classes and used Generics for instantiation.
Reference: https://www.typescriptlang.org/docs/handbook/generics.html#using-class-types-in-generics
See sample code below:
Base Class (abstract.control.ts)
export type AbstracControlOptions = {
key?:string;
}
export abstract class AbstractControl {
key:string;
constructor(options:AbstracControlOptions){
this.key = options.key;
}
}
Parent Class (container.ts)
import { AbstractControl, AbstracControlOptions } from './abstract.control';
import { Factory } from './factory';
export { AbstracControlOptions };
export abstract class Container extends AbstractControl {
children: AbstractControl[] = [];
constructor(options: AbstracControlOptions) {
super(options);
}
addChild(options: { type: string }) {
var Control:any = Factory.ControlMap[options.type];
if (Control) {
this.children.push(Factory.create(Control, options));
}
}
}
I don't have to import the child classes any more, because I'm using factory.ts to instantiate the child classes.
Factory Class(factory.ts)
import {AbstractControl, AbstracControlOptions} from './abstract.control';
type ControlMap<T extends AbstractControl> = {
[type:string]:T
};
export class Factory{
static ControlMap: ControlMap<any> = {};
static create<T extends AbstractControl>(c: { new ({}): T; }, options: AbstracControlOptions): T {
return new c(options);
}
}
Although class constructor seems to be called at c: { new ({}): T } but it does not actually calls it. But gets the reference to the constructor via new operator. The parameter {} to the constructor in my case is required because the base class AbstractControl requires it.
(1) Child Class(layout.ts)
import { Factory } from './factory';
import { Container, AbstracControlOptions } from './container';
export type LayoutlOptions = AbstracControlOptions & {
type:"layout";
}
export class Layout extends Container {
type: string = "layout";
constructor(options:LayoutlOptions) {
super(options);
}
}
Factory.ControlMap["layout"] = Layout;
(2) Child Class(repeater.ts)
import { Factory } from './factory'
import { Container, AbstracControlOptions } from './container';
export type RepeaterOptions = AbstracControlOptions & {
type: "repeater";
}
export class Repeater extends Container {
type: string = "repeater";
constructor(options:RepeaterOptions) {
super(options);
}
}
Factory.ControlMap["repeater"] = Repeater;

TypeScript modules

I am wondering if it is possible somehow to have two or more classes in two or more files added to the same module in TypeScript. Something like this:
//src/gui/uielement.ts
module mylib {
module gui {
export interface UIElement {
public draw() : void;
}
}
}
//src/gui/button.ts
///<reference path='uielement.ts'/>
module mylib {
module gui {
export class Button implements UIElement {
constructor(public str : string) { }
draw() : void { }
}
}
}
There will probably be dozens of GUI classes, so having them all in the same file will not be possible. And all my classes will be in the 'mylib' module.
But how do I do that?
If the module mylib {...} is translated into a function then all content of all mylib blocks in all files should be contained within the same function.
Is this at all possible?
When I compile I get this:
$ tsc src/gui/button.ts
src/gui/button.ts(4,39): The name 'UIElement' does not exist in the current scope
This is exactly how it works! If you look at the generated javascript code, it add as an anonymous function that accepts an object, the "the module object":
var mylib;
(function (mylib) {
var Button = (function () {
function Button(x) {
this.x = x;
}
return Button;
})();
mylib.Button = Button;
})(mylib || (mylib = {}));
If you look at the last line (})(mylib || (mylib = {}));) you see that it instantiates a new ojbect (mylib = {}) only if the existing variable is false (or something that evaluates to false, like null).
That way, all "modules" that are named the same will be merged to the same object.
Therefore, internal modules extend each other. I have to note that I have not quite figured out what happens to nested modules.
Update: Your code works for me if I do not use the nested module syntax, but change it to the dot syntax. e.g.:
module mylib.gui {
}
instead of
module mylib {
module gui {
}
}
I'll try to investigate in why this is happening, as far as I have read the spec, both ways should be equal.
Update: if the nested referenced module is marked as exported, it works:
module mylib {
export module gui {
}
}