Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

260
Views
Create class declaration programmatically in javascript?

Eventually what I need is to build a class declaration at runtime providing dynamic parameters to a property annotation:

import {Type} from "external-module";

export default class TypeWrapper {

    @Type(() => '{this part of the class declaration should be changable at runtime}')
    data

}

I have a feeling that this should be possible to achieve but can't figure out a proper way yet.

As a proof of concept I was trying to do something like below:

let MyClass = eval('(class MyClass{})')
let myClass = new MyClass()

That works, however MyClass needs to define some imports:

        let MyClass = eval('import {Type} from "external-module"' +
            '(class MyClass{})')

That one fails with "Cannot use import statement outside a module" which is quite expected.

Another approach I tried is to load a module from string:

        var moduleData = '' +
            'import module from "./module/path/file.js"\n' +
            '\n' +
            'export default class MyClass {\n' +
            '}\n' +
            '\n';
        var b64moduleData = "data:text/javascript;base64," + btoa(moduleData);


        let MyClass = await import(b64moduleData)

But it fails with "Cannot find module", suggesting it assumes b64moduleData is a path rather than module data itself.

Anyone has any suggestions?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Normally, for this type of thing I would use a class factory:

import { Type } from 'some-module';

function createClass(parameters) {
  return class {
    ....
  }
}

const MyClass = createClass(...);

I'm unsure if this fits your particular use case based on the details provided.

EDIT: As a side-note, as far as I know, you cannot construct modules from a string, which is what your code is doing, and what the compiler is complaining about.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!