在Typescript中动态定义常量

在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.


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

最佳答案

简而言之...不。Const是块作用域的。声明后才可用,直到那时才可用。如果您想声明某些东西是不可变的,那并不难,但是这个问题表明您可能缺乏知识。我认为您可能会发现更有用的是如何深度冻结对象,以使事物无法添加,删除或更改。但是它很浅,因此除非您要递归冻结(CAREFUL)或在路径上冻结它,否则深层更改将是一个问题

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 }

关于javascript - 是否可以在Typescript中动态定义常量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47360062/

10-13 00:33