How to transform a string into a template in TypeScript

I have a map of templates structured like this:

const templateMap = {
    greeting: `Hello, ${name}`,
    farewell: `Goodbye, ${name}`
  }

However, I am facing an issue where I need to apply the 'name' variable after defining the map. I came across a solution involving treating the templates as strings and utilizing

eval("`"+template+"`") 
, but I find this approach unappealing.

Is there a way to specify when the variables in the templates should be applied? Is there a method to convert a string into a pre-defined template?

Answer №1

Define the function map that generates an object:

const map = (name: string) => ({
    greeting: `hello ${name}`,
    farewell: `goodbye ${name}`
})

map('Octopus') // { "greeting": "hello Octopus",  "farewell": "goodbye Octopus" } 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am looking to transfer information from Angular 4 to Java servlet (cross-domain)

Having trouble sending data from Angular 4 to a Java servlet due to access control restrictions. Need to figure out how to properly insert data into the database using the Java servlet. Here is my code snippet: import { Injectable } from '@angular/ ...

Looking to retrieve the AssetLoadedFunc properties in the LoadAssets function? Wondering if you should use TypeScript or JavaScript

When I invoke this.AssetLoadedFunc within the function LoadAssets(callback, user_data) LoadAssets(callback, user_data) { this.glg.LoadWidgetFromURL("assets/Js/scrollbar_h.g", null, this.AssetLoaded, { name: "scrollb ...

Why aren't functions included when casting from a JSON literal to a specific type?

In my model class, the structure looks like this: export class Task { public name: string; public status: string = "todo"; public completeTask(): void { this.status = "done"; } } There is also a service responsible for retrie ...

Is there a way to incorporate a dropdown feature into a search bar using Ant Design?

I'm currently working on a project that requires me to incorporate two drop-down menus inside the search box. Despite following the guidelines provided in the documentation (https://ant.design/components/input), I encountered a problem when trying to ...

The function 'transformArticles' is not recognized as a property of the object 'Article'

I'm encountering an issue with Typescript that I need help understanding. In my code, I have a route where I am importing a class called Article like this: import { Request, Response } from "express"; const appRoot = require("app-root-path"); import ...

Updating shared variables is a challenge when passing functions as props to multiple functional components

In my work on implementing a navbar feature in the next.js framework, I have developed two functions for managing the mobile interface of the website. These functions handle the opening and closing of the navbar, utilizing a hamburger menu for opening and ...

The input text in the Typeahead field does not reset even after calling this.setState

As I work on creating a watchlist with typeahead functionality to suggest options as the user types, I encountered an issue where the text box is not resetting after submission. I attempted the solution mentioned in this resource by calling this.setState( ...

What is the best way to increase the size of an array and populate it with just one specific element in Types

If I want to create an array in Python, like [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], all I have to do is use [1] * 10. >>> [1] * 10 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] Is it possible to achieve the same result in TypeScript? ...

Dealing with router parameters of an indefinite number in Angular 5: A comprehensive guide

Is there a method to efficiently handle an unknown number of router parameters in a recursive manner? For instance: We are dealing with product categories that may have subcategories, which can have their own subcategories and so on. There are a few key ...

Unusual Interactions between Angular and X3D Technologies

There is an unusual behavior in the x3d element inserted into an Angular (version 4) component that I have observed. The structure of my Angular project is as follows: x3d_and_angular/ app/ home/ home.component.css hom ...

What is the best way to incorporate additional properties while utilizing useSession in Next.js with TypeScript?

I've encountered an issue while trying to add new properties using useSession() in a TypeScript environment. Although it works on console.log, there is an error related to the type mismatch. The useSession() function typically returns name, email, an ...

Having trouble organizing the date strings in the material table column

In my Angular application, I have a material table with multiple columns that I am sorting using matSort. While I can successfully sort the last two columns in ascending or descending order, I am facing an issue with the first column which contains date va ...

Dynamic addition of script to <head> element in Angular is a common task for many developers

I have explored some examples that illustrate how to dynamically add a script with a URL in Angular However, I am interested in adding this type of content to the <head> <script> !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(! ...

Using pipes to filter JSON data based on key value pairs

I have a collection of items in the specified structure: { img: './app/images/codeeval.png', title: 'CodeEval', repository: 'https://github.com/Shooshte/CodeEval', description: ...

Having trouble getting the backpack feature to work on Skyscanner's React app

I encountered an error while compiling my React app. Initially, I faced an old SSL security error on NodeJS, which I managed to fix with the help of Stack Overflow. However, now I am encountering a new error. Failed to compile. ./node_modules/@skyscanner/ ...

Ways to retrieve the ngValue from various select elements created in the HTML code

I'm dealing with a JSON list of roles that includes their id, name, and parent_id (referring to themselves). roles My goal is to display all the roles along with their names and corresponding parents. The parent will be displayed in a select input, ...

Tips on utilising the datepicker solely with the calendar icon, avoiding the need for any input fields

I'm currently working on a Datatable filter and I would like to incorporate a calendar icon to facilitate date filtering by simply clicking on the Datatable Header. At this stage, I've managed to display a calendar Icon on my Datatable header, b ...

Customizing the standard ping protocol for native JavaScript websockets

In my Expo (React Native) project, I am working on implementing a protocol to manage stale websocket connections on both the client and server sides. The 'ws' package offers built-in callback handling for the 'pong' event (and sending p ...

Express application (utilizing TypeScript) failing to handle routes efficiently

Encountering a technical issue : I am developing a REST API, but my application does not seem to trigger the actions when I send a request to the endpoint. This is my server configuration: import express, { Express } from 'express'; import c ...

Preventing runtime error in Next.js API routes by handling axios exceptions

I am currently working on creating an API route in Next.js that sends a request to my backend and saves the token in the cookies. However, I am facing an issue where 4xx responses are causing an Unhandled runtime error. Despite everything working correctly ...