Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

265
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda