Skip to content
Advertisement

Is it possible to dynamically define a constant in Typescript?

I am trying to find a way to dynamically define a constant in Typescript but I’am starting to thing it’s not possible.

I tried this :

  define(name: string, value: any): boolean {
    var undef;
    const name = value;
    return name == undef;
  }

I am supposed to call:

define ('MY_CONST_NAME', 'foo_value);

I get the following error :

Duplicate 'name' identifier.

I think it’s normal but i don’t know how to achieve my goal.

Advertisement

Answer

This question made no sense but there is a workaround to achieve this using types:

type Dynamyc = Record<string, string>

const myDynamicsVars: Dynamyc = {}

myDynamicsVars.name = “toto”

console.log(myDynamicsVars.name)

Advertisement