Reputation: 1065
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.
Upvotes: 1
Views: 3948
Reputation: 1065
This question made no sense but there is a workaround to achieve this using types:
type Dynamic = Record<string, string>
const myDynamicsVars: Dynamic = {}
myDynamicsVars.name = "toto"
console.log(myDynamicsVars.name)
Upvotes: 0
Reputation: 2052
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
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 }
Upvotes: 1