簡體   English   中英

Typescript可以動態定義一個常量嗎?

[英]Is it possible to dynamically define a constant in 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 是塊范圍的。 宣布后它就可用,直到那時才可用。 如果您想將某些東西聲明為不可變的,那並不難,但是這個問題可能表明您缺乏知識。 我認為您可能會發現更有用的是如何深度凍結 object,這樣就無法在其中添加、刪除或更改內容。 然而它很淺,所以深度變化將是一個問題,除非你想遞歸地(CAREFUL)或在路徑上凍結它

來自 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 }

這個問題沒有意義,但是有一種解決方法可以使用類型來實現:

類型 Dynamyc = Record<string, string>

const myDynamicsVars:Dynamyc = {}

myDynamicsVars.name = "toto"

console.log(myDynamicsVars.name)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM