是否可以在Typescript中动态定义常量?

时间:2017-11-17 22:13:43

标签: javascript typescript

我试图找到一种在Typescript中动态定义常量的方法,但我开始认为它是不可能的。

我试过了:

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

我应该致电:

define ('MY_CONST_NAME', 'foo_value);

我收到以下错误:

Duplicate 'name' identifier.

我认为这很正常,但我不知道如何实现我的目标。

1 个答案:

答案 0 :(得分:1)

简而言之......编号Const是块范围的。当宣布它变得可用时,直到那时。如果你想宣称某些东西是不可变的,那就不那么难了,但这个问题可能表明缺乏知识。我认为您可能会发现更有用的是如何深度冻结对象,以便无法添加,删除或更改对象。然而它很浅,所以深度变化将是一个问题,除非你想以递归方式(小心)或在路径上冻结它

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 }