gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:58:39 26 4
gpt4 key购买 nike

我正在尝试找到一种在 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 是 block 作用域的。宣布后它就可用,直到那时才可用。如果您想将某些东西声明为不可变的,那并不难,但是这个问题可能表明您缺乏知识。我认为您可能会发现更有用的是如何深度卡住一个对象,这样就无法在其中添加、删除或更改内容。然而它很浅,所以深度变化将是一个问题,除非你想递归地(小心)或在路径上卡住它

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com