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

tjvv9vkg  于 2022-11-30  发布在  TypeScript
关注(0)|答案(2)|浏览(144)

我试图找到一种在Typescript中动态定义常量的方法,但我开始觉得这是不可能的。
我试过这个:

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

我应该叫:

define ('MY_CONST_NAME', 'foo_value);

出现以下错误:

Duplicate 'name' identifier.

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

7gcisfzg

7gcisfzg1#

简而言之......不。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 }
kzipqqlq

kzipqqlq2#

这个问题毫无意义,但有一个解决方法可以使用类型来实现:
type Dynamyc =记录〈字符串,字符串〉
常量myDynamicsVars:动态c = {}
myDynamicsVars.name 托托”
控制台日志myDynamicsVars.name)

相关问题