简体   繁体   中英

Constructor error using namespace in Typescript

I'm trying to use constructors inside a class using namespace, but every time I want to push an object into array, i get an typerror, this doesn't happen when I'm not using namespace

why i'm getting this error just for use namespace?

these are my test classes

1.ts

namespace pruebas {

export class User {

    private _name: string;
    private _ape: string;
    constructor(name,ape){
        this._name = name;
        this._ape = ape;
    }

    get name(): string {
        return this._name;
    }

    set name(value: string) {
        this._name = value;
    }

    get ape(): string {
        return this._ape;
    }

    set ape(value: string) {
        this._ape = value;
    }
}
}

2.ts

///<reference path="1.ts"/>
namespace pruebas {
import pr = pruebas.User;

let us = new User(`saresease`, `ssfse`);
let vw = new User(`ghrebbre`, `bnerev`);
let r =[]
r.push(us,vw);
console.log(r)
}

This is the error

    var us = new pruebas.User("saresease", "ssfse");
         ^

TypeError: pruebas.User is not a constructor
at pruebas (C:\Users\Downloads\ts project\src\testnames\2.js:4:14)
at Object.<anonymous> (C:\Users\Downloads\ts project\src\testnames\2.js:9:3)
at Module._compile (module.js:556:32)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3)
at Module.runMain (module.js:590:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)

You need to compile with --outFile for this to work.

More generally, since you're running a node process, you shouldn't be putting things into the global namespace, as this won't really work for long (as soon as you need to import some other thing, this all falls apart). Use top-level export and import declarations to share components between files.

See also How do I use namespaces with TypeScript external modules?

you can use namespace in a module after you export it.

1.export the namespace in 1.ts .

export = pruebas;

2.import the namespace using import=require(..) in 2.ts .

import pruebas=require("./1.ts");

you can use namespace as global library.

you must compile 2.ts & 1.ts into a single script file.if you define 1.ts as both global library and a module,you must specify a module loader via option --module=amd / --module=system when using tsc compile .ts into a single .js file.

  1. using triple-slash directive to define your dependency in 2.ts .

     ///<reference path="./1.ts"/>; 
  2. compile the 2.ts with tsc --outFile 2.js <srcRoot>/2.ts ,then add the js in browser you can see the result.if you want to see details, let's go!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM