Search code examples
javascriptarraysjsontypescriptstring-interpolation

typescript get value from stringObject that has stringInterpolation and fill the interpolation;


Example:

const objectA = {
  a: `a ${fruit} is red`,
  b: 42,
  c: false
};

const fruit = 'strawberry';

console.log(objectA['a']);

Console:

Error: fruit is not defined

I'm wondering if this is even possible.

If it is how could I do this.


Solution

  • You can do this, but you have to do it in the right order:

    const fruit = 'strawberry';
    
    const objectA = {
      a: `a ${fruit} is red`,
      b: 42,
      c: false
    };
    
    console.log(objectA['a']);