Variables File:
export class VariableSettings {
public static string_value: string = 'vikas/${id}/data';
}
Other File.
import {VariableSettings} from './variables';
getData(id:string ){
console.log(`${VariableSettings.string_value}`, `${id}`);
// it prints vikas/${id}/data abcd11123
}`
Now I want the result like that "vikas/abcd11123/data". So how can I inject the id in that string.
Any suggestion regarding the same will be appreciated.
Thanks
You can add values into a JavaScript string using a template literal. This is a dollar sign followed by a pair of curly brackets. Within the curly brackets should be the expression whose value you want to embed in the string.
Rules and Regulations for TypeScript String Interpolation String Interpolation replaces the placeholders with values of string literals of any type. As these are very useful in the modern programming language, in TypeScript, they are enclosed using backticks “ which denotes the string's start and end.
So anything that works in JavaScript is also valid in TypeScript. And since TypeScript does not have its own syntax for string interpolation, any explanation from JavaScript applies here as well.
In JavaScript, the template string implements the string interpolation. A template string is defined by wrapping a sequence of characters into a pair of backticks `I'm template string` . The template string placeholders have the format ${expression} , for example `The number is ${number}` .
To use interpolated strings you need to use the ``
string separator as you do in your second snippet. If you already used a non interpolated string to hold the value of your setting, there is no way you can then interpolate it using the interpolation feature (you could use a regex to perform replacement but that is a bit messy).
The simplest solution is to make the field a function and have id
as a parameter
export class VariableSettings {
public static USER_BOOKINGS = (id: number) => `vikas/${id}/data`;
}
console.log(`${VariableSettings.USER_BOOKINGS(10)}`);
console.log(VariableSettings.USER_BOOKINGS(10)); // Or no interpolation at call site, not needed anymore if you just need the single value
The USER_BOOKINGS
will now be a function that takes as arguments the parameters needed to construct the string. This way the parameters needed for the strings are clear and type-safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With