2

How can I instantiate a class (with, say, a known empty constructor), for example:

at api/EmptyClass1.ts, I have:

export default class EmptyClass1 {

}

and, at api/EmptyClass2.ts, I have:

export default class EmptyClass2 {

}

I want this function:

function(filepath:string):any{
  return Object.fromFile(filepath); //this line is mock code
}

to return a new instance of either EmptyClass1 or EmptyClass2, if the parameter filepath:string is "api/EmptyClass1.ts" or "api/EmptyClass2.ts", respectively.

The files defining the classes may not be known at the time the function is written may include any number of files. Consequently, using the import statement for each class, then using a switch, or if-then statements is not an acceptable solution.

The .ts files defining the classes are transcoded to javascript and reside in the application .build folder as .js files.

I am using typescript on node.js (recent versions).

Anon21
  • 2,961
  • 6
  • 37
  • 46

1 Answers1

2

Use require instead, and your problem will be solved. If the file may not exist, you can use optional-require if you want to have a fallback without using try/catch.

    function fromFile(filepath:string):any{
      // return Object.fromFile(filepath); //this line is mock code
      return require(filepath);
    }

Or just call require directly instead of wrapping it in another function.

Also check: nodejs require inside TypeScript file

Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
  • Is there any way to call require in a non-blocking manner? I assume this call is synchronous when used at runtime, and that it reads the file from the disk. – Anon21 Dec 26 '19 at 15:53
  • There is not, but require calls are cached, so each file will only be called once, and unless the files are huge, I don't think you'll have to worry. You can preload them dynamically if you want, before you start the server too. – Marcos Casagrande Dec 26 '19 at 15:57
  • require will only work if file exist in your project, what if file exist outside the project in that case, Any suggestion how to do that? – Vimal Patel Jan 15 '21 at 07:48