简体   繁体   中英

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.

In short... No. Const is block scoped. When declared it becomes available and not until then. If you want to declare something as immutable it's not that hard, but this question shows a lack of knowledge possibly. I think what you may find more useful is how to deep freeze an object so things can't be added to, taken off of, or changed in it. However it is shallow, so deep changes would be an issue unless you want to freeze it recursively(CAREFUL) or on a path

From the MDN :

var obj = {
  prop: function() {},
  foo: 'bar'
};

// New properties may be added, existing properties may be
// changed or removed
obj.foo = 'baz';
obj.lumpy = 'woof';
delete obj.prop;

// Both the object being passed as well as the returned
// object will be frozen. It is unnecessary to save the
// returned object in order to freeze the original.
var o = Object.freeze(obj);

o === obj; // true
Object.isFrozen(obj); // === true

// Now any changes will fail
obj.foo = 'quux'; // silently does nothing
// silently doesn't add the property
obj.quaxxor = 'the friendly duck';

// In strict mode such attempts will throw TypeErrors
function fail(){
  'use strict';
  obj.foo = 'sparky'; // throws a TypeError
  delete obj.quaxxor; // throws a TypeError
  obj.sparky = 'arf'; // throws a TypeError
}

fail();

// Attempted changes through Object.defineProperty; 
// both statements below throw a TypeError.
Object.defineProperty(obj, 'ohai', { value: 17 });
Object.defineProperty(obj, 'foo', { value: 'eit' });

// It's also impossible to change the prototype
// both statements below will throw a TypeError.
Object.setPrototypeOf(obj, { x: 20 })
obj.__proto__ = { x: 20 }

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM