2017-11-17 151 views
1

我想找到一種方法來在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. 

我認爲這是正常的,但我不知道如何實現我的目標。

+3

你收到這個錯誤,因爲你有一個函數參數:然而,它是淺的,所以除非你想凍結它遞歸(小心)或路徑

From the MDN上的深刻變化將是一個問題和一個同名的局部變量。使用不同的名稱,或者說明你想要完成什麼 –

+1

我們需要更多的上下文(例如,你會怎麼稱呼'define')。這裏錯誤是正常的,你在函數參數和範圍內定義了'name'。 – ValLeNain

+0

我明白了,但我只是想在我的函數中創建一個常量並返回一個布爾值,如果我成功與否 – DMCISSOKHO

回答

1

簡而言之編號Const是塊範圍。當宣佈它變得可用時,直到那時。如果你想聲明一些不可變的東西並不難,但這個問題可能表明缺乏知識。我認爲你可能會發現更有用的是如何深度凍結一個對象,以便無法添加,刪除或更改對象。

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 } 
+0

啊啊謝謝你:「這個問題表明缺乏可能的知識」,順便說一句,這是一個很好的答案,我很確定我正在嘗試一些不可能的事情。 – DMCISSOKHO

相關問題