Search code examples
javascriptangulartypescripteval

How to eval code as string to class name in javascript?


I'm trying to deserialize my URL parameters that contains a class name and then to test existing object against that class.

I thought I could retrieve the actual class with an eval like this

let type = eval(this.route.snapshot.queryParams['type']);
let id = +this.route.snapshot.queryParams['type'];

this.selectedResult = this.data.find(x => x.constructor === type && x.id === id);

But eval throws:

Uncaught ReferenceError: MyClass is not defined

Indeed, when I put a breakpoint on the eval line, my business classes are not defined.

My guess is that the import does not really import the classes because it's only used to check types before compilation.

How can I do?


Solution

  • You could just check the constructor name:

    x.constructor.name === this.route.snapshot.queryParams['type']
    

    As a bonus this would be less a security risk for your users (your user's browser isn't evaling a random string which could have been given in for example in a link in a mail).

    It still doesn't sound like a good idea to pass unfiltered code references in an URL: what if the actual class name changes ?