1

Here is my code

// properties.ts
export const properties = {
    title: "Google"
};

// example.ts
import { properties } from './properties.ts';

console.log(properties.title); // Prints Google
console.log(eval("properties.title")); // Expected to print Google but throws ReferenceError: properties is not defined

However, console.log(eval('properties_1.properties.title')) // Prints Google

But how to derive "properties_1" is my concern.

1 Answer 1

3

The import statement in TS transpiles to a new variable. This is by default in typescript and eval cannot compute that.

I tried like this and it worked,

import { properties } from './properties';
let p = properties;
console.log(p.title); // Prints Google
console.log(eval('p.title'));

Another way you can do this by importing properties into variable,

import * as properties  from './properties';
console.log(properties.properties.title); // Prints Google
console.log(eval('properties.properties.title')); // Prints Google

Make sure you compile this way,

>tsc dynamic.ts -t ES6 -m commonjs
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.