首页 > 解决方案 > 使用 TypeScript 冻结导出

问题描述

我认为这是最好的方法:

export const stdMarker = '@json-stdio';
export const stdEventName = '@json-stdio-event';

Object.defineProperties(module.exports, {
  'stdMarker': {
     writable: false
   },
  'stdEventName': {
     writable: false
  }
});

有什么速记吗?如果 TS 提供类似的东西会很有趣:

export frozen const stdMarker = '@json-stdio';
export frozen const stdEventName = '@json-stdio-event';

管他呢。有一个更好的方法吗?

标签: javascriptnode.jstypescripttypescript2.0tsc

解决方案


Since you've defined stdMarker and stdEventName as const (and their value is a primitive, not an object) you should have the desired behavior out of the box. When importing the const in another file, and attempting to modify it, I get an error:

Cannot assign to 'test' because it is not a variable.

What behavior do you expect from a frozen export? Your defineProperties call is doing a similar thing to const in this situation.


推荐阅读