1

I have extracted all strings from my code and put them into a file called constants.ts ..

export class Constants {
  public static API_URL = '/api/';
  public static CREATE_CHILD_API_URL = Constants.API_URL + '%s' + '/create-child';
}

I'm able to substitute a value into the string using console.log:

import { Constants } from '../common/constants';
console.log(Constants.CREATE_CHILD_API_URL, 'dummyId');

Produces this in console: /api/dummyId/create-child which is the goal.

How can I do the same but store the result in a variable for later use?

Is there something I can use that is native and runs on modern browsers without having to pull in a lib?

Template literals don't seem to suite the use case since the variable will not be defined in my constants file.

bobbyrne01
  • 6,295
  • 19
  • 80
  • 150

1 Answers1

2

You will eventually make a mistake with this approach. I would rather recommend to use functions with certain parameters which will generate strings you need by executing strings interpolation inside:

export class Urls {
  public static API_URL = '/api/';
  public static CREATE_CHILD_API_URL =
      (id: string) => `${Urls.API_URL}${id}/create-child`;
}

Later you will be able to use it like this:

import { Urls } from '../common/urls';
const forLaterUse = Urls.CREATE_CHILD_API_URL('dummyId');
console.log(forLaterUse);
Pavel Agarkov
  • 3,633
  • 22
  • 18