Home > database >  Use/convert a string to template in TypeScript
Use/convert a string to template in TypeScript

Time:12-15

I have a map of templates like this:

public map = {
    hi: `hi ${name}`,
    bye: `bye ${name}`
  }

but I need to apply the name variable after the declaration of the map. I found a way, declare the templates as a string and do eval("`" template "`") but this is uggly.

There is a way to specify when the templates apply the template? there is a way to convert a string to a template?

CodePudding user response:

Define map as a function that returns an object:

const map = (name: string) => ({
    hi: `hi ${name}`,
    bye: `bye ${name}`
  })

map('Squid') // { "hi": "hi Squid",  "bye": "bye Squid" } 
  • Related